我正在尝试将我的代码封装在一个即时函数中,稍后将通过全局变量 x 访问该函数并充当“模块”。
代码:
var x = (function () {
console.log(x); // undefined
console.log(this); // undefined
})();
但我不明白为什么我不能使用 this
来引用函数本身。
编辑:
立即函数在严格模式(“use strict”
)下的另一个函数中
最佳答案
当一个函数在一个函数内执行,或者作为回调传递给另一个在 strict mode 中处理的函数时,会发生一件有趣的事情。
here's a demo , 并观察控制台
function foo(){
'use strict';
(function(){
//undefined in strict mode
console.log('in foo, this is: '+this);
}());
}
function bar(){
(function(){
//DOMWindow when NOT in strict mode
console.log('in bar, this is: '+this);
}());
}
foo();
bar();
因此,如果该代码在严格模式下的另一个函数中作为回调执行,this
将不会引用全局 window
,而是 未定义
。
关于javascript - 如何在立即函数中使用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10120691/