I have done a fair amount of programming in JavaScript/JQuery.
But I never used "prototype". In fact, I have no clue what it means.
Do you have a practical example when it is useful?
-
5It could mean 2 things: a javascript framework, and a javascript method to extend and define objects. The two are completely different. Not sure which one of the two you mean.Darin Dimitrov– Darin Dimitrov2011年09月05日 21:30:11 +00:00Commented Sep 5, 2011 at 21:30
-
This question is ambiguous. The lib or the obejcts property?user278064– user2780642011年09月05日 21:30:12 +00:00Commented Sep 5, 2011 at 21:30
-
1You should probably read: MDN - Introduction to Object-Oriented JavaScript.Felix Kling– Felix Kling2011年09月05日 21:36:24 +00:00Commented Sep 5, 2011 at 21:36
-
1possible duplicate of How does JavaScript .prototype work?, stackoverflow.com/questions/7165109/…, stackoverflow.com/questions/6554207/javascript-prototypeuser113716– user1137162011年09月05日 21:39:21 +00:00Commented Sep 5, 2011 at 21:39
-
stackoverflow.com/questions/6256321/…user113716– user1137162011年09月05日 21:45:21 +00:00Commented Sep 5, 2011 at 21:45
2 Answers 2
Simplest example:
function Foo() {
this.bar = function() {
return 42;
}
}
Now you can create as many instances of Foo as you want and call bar():
var a = new Foo();
var b = new Foo();
Even though both object have bar() method which is exactly the same in both cases, these are distinct methods. In fact, each new Foo object will have a new copy of this method.
On the other hand:
function Foo() {}
Foo.prototype.bar = function() {
return 42;
}
has the same end result but the function is stored only once in object prototype rather than in an object itself. This may be a deal breaker if you create tons of Foo instances and want to save some memory.
Comments
Assuming you are asking about Object.prototype,
All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.