立即调用函数表达式 (IIFE) 与非 [英] Immediately-Invoked Function Expression (IIFE) vs not

查看:26
本文介绍了立即调用函数表达式 (IIFE) 与非的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多这样的代码:

I see a lot of code like:

var myApp ={};
(function() {
    console.log("Hello");
    this.var1 = "mark";     //"this" is global, because it runs immediately on load.  Caller is global
    myApp.sayGoodbye = function() {
        console.log("Goodbye");
    };
})();

这会导致匿名函数立即执行.但是,与仅将代码内联相比,这样做的优势是什么?

Which causes the anonymous function to execute immediately. But what is the advantage of this, compared to just putting the code inline?

var myApp ={};
console.log("Hello");
var1 = "mark";     
myApp.sayGoodbye = function() {
    console.log("Goodbye");
};

显然是和函数的作用域有关,但是由于函数是匿名的并且被窗口调用,所以它的作用域(即this)是全局的,不是吗?

Apparently it's to do with scope of the function, but as the function is anonymous and called by window, it's scope (i.e. this) is global, no?

推荐答案

通常,你会有这样的:

        var myApp ={};
        (function() {
            console.log("Hello");
            var var1 = "mark";  
            myApp.sayGoodbye = function() {
                console.log("Goodbye");
            };
        })();

主要区别在于 var1 不会弄乱全局命名空间.这次调用之后,var1 还是和之前一样(一般是未定义的).

The main difference is that var1 doesn't clutter the global namespace. After this call, var1 is still the same than before (generally undefined).

由于 var1 只能从闭包中定义的函数中访问,因此称为私有".

As var1 can only be accessed from the function defineds in the closure, it is said "private".

除了避免可能的冲突原因外,在无用时不保留全局变量更干净.

Apart avoiding possible causes of conflicts, it's just cleaner not to keep global variables when useless.

在这里,您没有局部变量,而是定义为 this.var1 的全局变量.这可能是一个错误,或者可以在代码的其他地方找到原因.

Here, you don't have a local variable but a global one defined as this.var1. It's probably a bug, or the reason would be found elsewhere in the code.

这篇关于立即调用函数表达式 (IIFE) 与非的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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