例如
var MyClass = function(){
var that = this;
var my_var = "I want this";
var another_var = "this one is easy";
this.aPublicFunc = function(my_var){
console.log(my_var); // logs "I don't want this";
console.log(another_var); // logs "this one is easy";
console.log(this.my_var); // logs undefined which makes sense as the this context is the context of the calling function.
console.log(that.my_var); // logs undefined
};
};
var an_object = new MyClass();
var an_object.aPublicFunc("I don't want this");
答案 0 :(得分:2)
不要覆盖它。它使代码的可读性更低,更容易混淆。
答案 1 :(得分:2)
与my_var
一样的私有变量只能从构造函数中的代码和调用它们的范围内定义的函数(如aPublicFunc()
)中访问。而且,要访问它们,您必须使用正常的javascript引用它们。当您使用相同的名称定义aPublicFunc()
的参数时,您隐藏该外部范围变量,并且无法按照定义到达它。这些私有变量不是对象的成员,它们是在闭包中捕获的变量。在javascript中,在闭包中访问变量的唯一方法是从该闭包范围内的代码中获取,如果没有任何内容覆盖它们的名称,则只能访问它们。
您的简单解决方案是将参数或局部变量的名称更改为略有不同的名称。如果你真的希望它们看起来相似,那么在它们之一的前面放一个下划线:
var MyClass = function(){
var that = this;
var _my_var = "I want this";
var _another_var = "this one is easy";
this.aPublicFunc = function(my_var){
console.log(_my_var); // logs "I want this";
console.log(_another_var); // logs "this one is easy";
console.log(my_var); // logs "I don't want this"
};
};
var an_object = new MyClass();
var an_object.aPublicFunc("I don't want this");
或者让这个论点更加明显:
var MyClass = function(){
var that = this;
var my_var = "I want this";
var another_var = "this one is easy";
this.aPublicFunc = function(new_my_var){
console.log(my_var); // logs "I want this";
console.log(another_var); // logs "this one is easy";
console.log(new_my_var); // logs "I don't want this"
};
};
var an_object = new MyClass();
var an_object.aPublicFunc("I don't want this");
您可以在此处查看最后一项工作:http://jsfiddle.net/jfriend00/Jeaaz/