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

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

问题描述

我看到很多代码,如:

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");
};

显然这与函数的范围有关,但是由于函数是匿名的,它的范围(即这个)是全局的,不是?

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).

As 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.

这里,您没有局部变量,而是定义为的全局变量。 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)vs不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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