这里我做了两个对象;一个在构造函数中创建访问器方法,另一个在原型(prototype)中创建。为什么人们会选择其中之一而不是另一个?
function spy1(name){
this.name = name;
var secret;
this.setSecret = function(message){
secret = message;
};
this.getSecret = function(){
return secret;
};
}
function spy2(name){
this.name = name;
this.secret;
/* (see comment) was:
var secret;
*/
}
spy2.prototype.setSecret = function(message){
this.secret = message;
/*was:
secret = message;
*/
};
spy2.prototype.getSecret = function(){
return this.secret;
/*was:
return secret;
*/
};
bond = new spy1("007");
smart = new spy2("86");
bond.setSecret("CONTROL is a joke.");
smart.setSecret("The British Secret Service is for sissies.");
最佳答案
主要区别在于,在您的第一个示例中,没有原型(prototype),getSecret
和 setSecret
函数实现将驻留在 spy1 的每个实例上.
在你的第二个例子中,函数定义在原型(prototype)上,所有实例都直接引用它们,你可以测试它:
var bond = new spy1("007"),
bond2 = new spy1("007");
bond.getSecret === bond2.getSecret; // <-- false since they are two functions
var smart = new spy2("86"),
smart2 = new spy2("86");
smart.getSecret === smart2.getSecret; // <-- true since is the same function
// on all instances
另请注意@T.J.评论说,在你的第二个例子中,使用原型(prototype),你无权访问构造函数闭包,为此你正在创建一个 window.secret
全局变量。
如果您打算使用 privileged methods ,扩展原型(prototype)不是一个选项,所有需要访问在构造函数范围内定义的变量的方法都需要在其中声明...
另请参阅:Closures .
关于javascript - Prototype vs. Not,有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1319325/