在我的回答中,我提到JavaScript闭包的“公共”属性不能在“私有”函数中访问。在A JavaScript VM that interprets code written in JSON中给出了一个例子。
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
必须属于全局对象。因此,公共函数只是一个分配给this
属性的匿名函数。这就解释了为什么调用publicfunction
会失败,因为它需要先引用this
。
然而,以下修复仍然无效:
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;
}
现在进入问题环节。这种行为背后的原因是什么?通过禁止未明确指定访问this
属性,它试图避免什么?
更新:问题的主要部分是:当解释器在作用域链中找不到名称时,为什么不应查看this
属性?
this
对象? - Earth Engine