开发者

JavaScript prototypes [duplicate]

This question already has answers here: Closed 12 years ago.开发者_如何转开发

Possible Duplicate:

JavaScript: Class.method vs. Class.prototype.method

What's the difference between creating a prototype like this:

Date.foo = function(bar) {
    alert(bar);
};

And this:

Date.prototype.foo = function(bar) {
    alert(bar);
};

Why/when should I use either?


in the first example, foo is a constructor method, its like a 'static' method in java. The second is like defining a method foo on a class -- it is scoped to the instance.

you would access the first like

Date.foo()

and the second like

Date d = new Date()
d.foo() 

or in another method on an instance of Date like

this.foo()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜