这里我做了两个对象;一个在构造函数中创建了存取方法,另一个在原型中创建。为什么会选择其中之一呢?原型与非,有什么好处?
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.");
请注意,在您的原型案例中,您(可能是无意中)创建了一个隐式全局变量'secret',它与构造函数中声明的(和未使用的)'secret'变量没有任何关系。该全局变量(全局对象的一个属性)是全局变量,将被'spy2'的所有实例共享 - 我猜这不是你想要做的。 – 2009-08-23 19:42:37
谢谢。那确实是无意的。我改变了代码;这现在是正确的吗? 所以真的,原型不能修改对象的私有变量。 – 2009-08-23 19:53:46