简单地说,这两段代码之间有什么区别吗,有什么理由使用其中一段而不是另一段吗?
代码 #1:
var thing=function(){}
thing.prototype={
some_method:function(){
alert('stuff');
}
}
代码 #2:
var thing=function(){}
thing.prototype.some_method=function(){
alert('stuff');
}
这是一样的。没有理由会有所不同。
但在我看来,最好使用第二种形式,因为如果您决定让thing
"类"继承另一个"类",那么您需要更改的更少:
thing.prototype = new SuperThing(); // inherits from the SuperThing class
thing.prototype.some_method=function(){
alert('stuff');
}
它还使得在多个 JavaScript 文件中定义类变得更加容易。
由于保持代码的连贯性更好,我宁愿始终使用相同的结构,即thing.prototype.some_method=function(){
结构。