Follow my code,
Apple is define function by prototype.
Banana is define function by class property.
var Apple = function(){} Apple.prototype.say = function(){ console.debug('HelloWorld'); } var Banana = function(){ this.say = function(){ console.debug('HelloWorld'); } } var a = new Apple(); var b = new Banana(); a.say(); b.say();
Are these difference ?
Classes. The most important difference between class- and prototype-based inheritance is that a class defines a type which can be instantiated at runtime, whereas a prototype is itself an object instance.
While a function definition specifies how the function does what it does (the "implementation"), a function prototype merely specifies its interface, i.e. what data types go in and come out of it.
Well not exactly. Prototypes are a special type of object and exist as a property on function-objects. When we try to access a key on a function-object, JavaScript will look at its prototype property to see if it's there. If not it will go up the prototype-chain to try to find it.
The __proto__ property of Object. prototype is an accessor property (a getter function and a setter function) that exposes the internal [[Prototype]] (either an object or null ) of the object through which it is accessed.
When you create more than one instance of Apple, you will still only have only one instance of say()
in memory. However, when you create more than one instance of Banana, you will end up creating lots of instances of the say()
function.
That's why prototypes save memory. You also avoid the processing cost of creating and assigning the say()
function.
Also, if you change the parent object's properties, if the child does not replace that property, changes are visible from the child.
prototype members are like class membeprototype members are like class member, while when u define it other way its not a class member. So if you are creating lot of object of Apple all will be sharing same function, while in case of banana, every object will have their own copy of function. Think prototype in javascript as static in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With