我试图将我的代码封装在一个立即函数中,稍后将通过全局变量x访问该代码,并像一个“模块”.
码:
var x = (function () { console.log(x); // undefined console.log(this); // undefined })();
但我不明白为什么我不能用它来引用函数本身.
编辑:
解决方法
当函数在函数内执行时,或者作为回调传递给在
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();