javascript – 如何在立即函数中使用“this”

前端之家收集整理的这篇文章主要介绍了javascript – 如何在立即函数中使用“this”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将我的代码封装在一个立即函数中,稍后将通过全局变量x访问该代码,并像一个“模块”.

码:

var x = (function () {

    console.log(x); // undefined
    console.log(this); // undefined

})();

但我不明白为什么我不能用它来引用函数本身.

编辑:

立即函数在严格模式下的另一个函数内(“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();​

因此,如果该代码在另一个处于严格模式的函数中作为回调执行,则不会引用全局窗口,而是将其定义为未定义.

猜你在找的JavaScript相关文章