What is the difference between the prototype function and the class property?

Follow my code
Apple defines the function as a prototype.
A banana defines a function by a 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 differences?

+44
javascript prototype
May 6 '11 at 13:58
source share
2 answers

When you create multiple instances of Apple, you will only have one instance of say() in memory. However, when you create multiple instances of the banana, you will create many instances of the say() function.

That's why prototypes save memory. You also avoid the cost of processing to create and assign the say() function.

In addition, if you change the properties of the parent, if the child does not replace this property, the changes will be visible from the child.

+65
May 6 '11 at 14:10
source share

Prototype elements are similar to members of the membeprototype class as a member of the class, while u defines it in a different way, rather than as a member of the class. Therefore, if you create many Apple objects, everyone will use the same function, whereas in the case of a banana, each object will have its own copy of the function. Think of a prototype in javascript as static in C #.

+2
May 6 '11 at 14:12
source share



All Articles