Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between define function by prototype and class property?

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 ?

like image 475
diewland Avatar asked May 06 '11 13:05

diewland


People also ask

What is difference between class and prototype?

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.

What is the difference between function prototype and function definition JavaScript?

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.

What is the difference between prototype and object in JavaScript?

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.

Is __ proto __ a property?

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.


2 Answers

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.

like image 58
Tim Rogers Avatar answered Sep 21 '22 20:09

Tim Rogers


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#.

like image 45
Falaque Avatar answered Sep 23 '22 20:09

Falaque