javascript – 为什么无法在闭包中的私有函数中直接访问此属性?
作者:互联网
在我自己对A JavaScript VM that interprets code written in JSON的回答中,我说过无法在“私有”函数中访问JavaScript闭包的“公共”属性.
该帖子中给出的例子是
function anobject(){
var privatefunction = function(){
//publicfunction(); //wrong; you have no access to it
console.log(this); //refer to the global object, not the object creating
};
this.publicfunction = function(){
console.log(this); //refer to the object creating
}
}
我认为原因是一些向后兼容性问题,privatefunction必须属于全局对象.因此,public函数只是一个分配给它的属性的匿名函数.这解释了为什么调用publicfunction会失败,因为它需要首先引用它.
但是,以下修复仍然无法正常工作:
function anobject(){
var privatefunction = function(){
//publicfunction(); //wrong; you have no access to it
console.log(this); //refer to the object creating
}.bind(this);
this.publicfunction = function(){
console.log(this); //refer to the object creating
}
}
当我明确指出privatefunction应该与创建对象绑定时,调用publicfunction应该可以工作,但事实并非如此.我必须做以下事情:
function anobject(){
var privatefunction = function(){
this.publicfunction();
console.log(this); //refer to the object creating
}.bind(this);
this.publicfunction = function(){
console.log(this); //refer to the object creating
}
}
另一种解决方法(我使用的方式)如下:
function anobject(){
var privatefunction = function(){
publicfunction();
console.log(this); //refer to the object creating
};
var publicfunction = function(){
console.log(this); //refer to the object creating
}
this.publicfunction = publicfunction;
}
现在是问题的一部分.这种行为背后的原因是什么?如果没有明确的规范,禁止访问这些属性,它试图避免什么?
更新:问题的主要部分是:当解释器在作用域链中找不到名称时,为什么不应该查看这些属性?
解决方法:
这里的问题是引用这是由函数/方法的调用者决定的,例如:
function anobject(){
// here "this" is the object
var privatefunction = function(){
// here "this" is the object **that called privatefunction()**
};
this.publicfunction = function(){
// this method will always be called by the object, so "this" is the object
}
}
为了实现你想要的你也可以试试这个:
function anobject(){
var that = this;
var privatefunction = function(){
[do what you like using "that"]
};
this.publicfunction = function(){
[here you can use "this" directly, or "that"]
}
}
另请参阅javascript范围如何工作,这里是What is the scope of variables in JavaScript?和网络上的.
标签:javascript,closures,language-design 来源: https://codeday.me/bug/20190901/1783845.html