在JavaScript中进行IIFE调用 [英] IIFE invocation in JavaScript

查看:104
本文介绍了在JavaScript中进行IIFE调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过的两种方法(我知道还有更多)使用IIFE:

Two methods I've seen (I know there are more) of using an IIFE:

(function(){
    console.log(this);
}).call(this);

(function(){
    console.log(this);
})();

有没有理由使用 .call(this)在第一个?不会(); 在函数中产生相同的上下文吗?

Is there any reason to use .call(this) on the first one? Won't (); yield the same context within the function?

推荐答案

这取决于代码的执行位置。

That depends on where the code is executed.

.call(this)显式设置到您传递给 .call 的对象。仅使用(); 设置为窗口(或者以严格模式 undefined

.call(this) explicitly sets the this to the object you pass to .call. Only using (); will set this to window (or to undefined in strict mode).

如果代码在全局范围内执行,它将是相同的。如果没有,那么如果这个没有引用窗口(或者是 undefined )。

If the code is executed in global scope it will be the same. If not, then you will get different results if this does not refer to window (or is undefined).

示例:

var obj = {
   foo: function() {
       (function(){
           console.log(this); // this === obj
       }).call(this); // this === obj

       (function(){
           console.log(this); // this === window
       })();
   }
};

obj.foo();

有关此MD c>的更多信息

这篇关于在JavaScript中进行IIFE调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆