我正在玩javascript对象来更好地理解"this"和函数上下文.我偶然发现了这个问题.我收到错误"obj2未定义",除非我在分配后运行window.obj2(),但我不知道为什么.将函数分配给window.obj2并不是立即执行它不应该足够吗?我知道你不应该污染窗口对象,这只是一个测试.谢谢!
window.obj2 = function(){
console.log('obj2 in window.object',this);
}
window.obj2(); // problem when this line is commented out
(function () {
var parent = {
obj : function(){
//console.log(this);
obj2();
this.obj2();
window.obj2();
},
obj2 :function(){
console.log('obj2 in parent',this);
}
}
parent.obj();
}());
Run Code Online (Sandbox Code Playgroud)
说明
OP询问为什么在定义它之后必须执行该函数以便稍后在代码中定义...看看当你注释掉问题行时会发生什么.
解开谜团:
你忘记了一个分号:
window.obj2 = function(){
console.log('obj2 in window.object',this);
}; // <--
Run Code Online (Sandbox Code Playgroud)
没有它,代码将被解释为
// I'm naming the functions to refer to them later
window.obj2 = function a(){
...
}(function b() { ... }());
Run Code Online (Sandbox Code Playgroud)
即括号周围b
被解释为调用操作的a
(就像你用b
自己:( function b() {...}()
).
引擎首先执行 b
以便将返回值作为参数传递给a
,并且仅在此之后将返回值赋值给window.obj2
.
所以,此刻b
被称为,window.obj2
确实还不存在.
因此,添加window.obj2()
使其工作的原因不是因为您正在访问window.obj2
,而是因为它使代码不具有暧昧性.以下括号不能再被解释为调用操作.你可以在那里使用任何声明,例如
window.obj2 = function(){
console.log('obj2 in window.object',this);
}
"foo";
(function () {
obj2();
}());
Run Code Online (Sandbox Code Playgroud)