I have done a fair amount of programming in JavaScript/JQuery.
But I never used "prototype". In fact, I have no clue what 开发者_StackOverflowit means.
Do you have a practical example when it is useful?
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.
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.
Read this and then probably this
精彩评论