如何访问公共函数中被公共函数覆盖的私有变量
例如
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");
For example
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");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像
my_var
这样的私有变量只能从构造函数中的代码以及调用时在其作用域内定义的函数(例如在aPublicFunc()
中)访问。而且,要访问它们,您必须使用普通的 javascript 引用它们。当您为aPublicFunc()
定义具有相同名称的参数时,您隐藏了该外部作用域变量,并且无法按定义访问它。这些私有变量不是对象的成员,它们是闭包中捕获的变量。在 javascript 中,访问闭包中的变量的唯一方法是从该闭包范围内的代码,并且只有在没有任何内容覆盖它们的名称的情况下才能访问它们。您的简单解决方案是将参数或局部变量的名称更改为稍微不同的名称。如果您确实希望它们看起来相似,请在其中一个前面加一个下划线,如下所示:
或者使参数更加明显,如下所示:
您可以在此处看到最后一项的工作:http://jsfiddle.net/jfriend00/Jeaaz/
Private variables like you have with
my_var
are only accessible from code in the constructor and from the functions defined inside their scope (like inaPublicFunc()
) when it is called. And, to access them, you have to use a normal javascript reference to them. When you define an argument toaPublicFunc()
with the same name, you hide that outer scope variable and there is NO way to reach it as defined. Those private variables are not members of the object, they are variables captured in a closure. In javascript, the only way to reach variables in a closure is from code in the scope of that closure and you can only reach them if nothing has overridden their name.Your simple solution is to change the name of the argument or the local variable to something slightly different. If you really want them to look similar, then put an underscore in front of one of them like this:
or make the argument a bit more obvious like this:
You can see this last one work here: http://jsfiddle.net/jfriend00/Jeaaz/
不要覆盖它。它使代码可读性更差并且更令人困惑。
Don't override it. It makes the code less readable and more confusing.