javascript 自调用匿名函数表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18203897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:04:19  来源:igfitidea点击:

A self invoking anonymous function expression

javascript

提问by Christoph

(function(){ ... })();

(function(){ ... })();

I HAVE looked at thispost and understood a bit about it. But there are few more doubts, mostly on how it is used.

我看过这篇文章,对它有所了解。但是还有更多的疑问,主要是关于它是如何使用的。



Like a Static block!

就像一个静态块!

since it acts like a static block(self invoking!), it can be used for initializing(like some make-believe constants)?

因为它就像一个静态块自调用!),它可以用于初始化(就像一些虚构的常量)?

But then there is no getteravailable to fetch anything from it and use it elsewhere!

但是,无法getter从中获取任何内容并在其他地方使用它!



return, Must?

返回,必须吗?

The solution to above is to HAVE a returnin that function? so that I can fetch whatever it returns and use that.

上面的解决方案是return在那个函数中有一个?这样我就可以获取它返回的任何内容并使用它。



reference to the global object?!

引用全局对象?!

(function(window, undefined){})(this);

(function(window, undefined){})(this);

The explanation for the above code was in the second answer of the referenced post, I couldn't understand it, If anyone can explain it more (or simpler for me), It will be great

上面代码的解释在参考帖子的第二个答案中,我无法理解,如果有人可以解释更多(或对我来说更简单),那就太好了



update: Take a look at this code ↓

更新:看看这个代码↓

var myElement=document.getElemetById("myElementId");
 (function(myElement){
      /**'this' here is 'myelement'???**/
 }; 
})(this);

回答by Christoph

A common metod is the following (called namespacing) - It created an encapsulated scope by immediately executing your function and returning the essential parts you need into your variable:

一个常见的方法如下(称为命名空间)——它通过立即执行你的函数并将你需要的基本部分返回到你的变量中来创建一个封装的作用域:

var yourNamespace = (function(window, undefined){ 
                    /* private code:*/
                    var privateVar = "foobar",
                        count = 0;
                    /* the stuff you want to use outside: */
                    return{
                       val: 5,
                       publicVar:privateVar,
                       func:function(){return ++count}
                    }
             })(this);// `this` is a reference to `window` here

This way you have access to everything you need via your yourNamespacevariable, while still maintaining privacy and not polluting the global object. It's called namespacing and uses the closure paradigm. You can also hand over functions to work with private (for the enclosing scope non-visible) variables.

这样你就可以通过yourNamespace变量访问你需要的一切,同时仍然保持隐私并且不会污染全局对象。它被称为命名空间并使用闭包范例。您还可以移交函数以使用私有(对于封闭范围不可见)变量。

One reason for handing over undefined was, that in ES3 undefined was writable, which it is not the case anymore in ES5. Handing over over thisas parameter shortens the lookup by creating a direct reference to the global windowobject in the scope. However, be very cautious - in ES5 strict mode thisis not the window anymore but resolves to undefined!! So this is not recommended anymore!

移交 undefined 的原因之一是,在 ES3 中 undefined 是可写的,而在 ES5 中则不再如此。this通过创建window对作用域中全局对象的直接引用,作为参数移交可以缩短查找时间。但是,要非常小心 - 在 ES5 严格模式下this不再是窗口而是解析为undefined!! 所以现在不推荐了!

Another reason for handing over window and undefined is that now that these are variable names, a minifier could compress them to a single letter.

移交 window 和 undefined 的另一个原因是现在这些是变量名,压缩器可以将它们压缩为单个字母。

if(myVar == undefined)
// could be compressed to:
if(a==x)

EDIT to your question:

编辑您的问题:

The thiswill not change in your example, you need one of the following solutions:

this在你的例子都不会改变,你需要以下解决方案之一:

(function(myElement){/*your code*/})( document.getElemetById("myElementId") );
// or:
(function(){
    var myElement = document.getElemetById("myElementId");
    /* your code */ 
})();

回答by robC

The main point of an iifeis to create an encapsulated scope. Otherwise, all the variables that you declare will end up in the global scope.
If you need to make something accessible from within that scope you can explicitly create a global namespace variable i.e. window.myApp = {}and attach it there i.e. window.myApp.myMethod = function(){...}
The reason for passing windowinto the iife is that it creates a local reference within the scope. That will shorten the lookup chain for better performance and the variable will also be minifiable.

一的主点iife是创建一个封装范围。否则,您声明的所有变量都将在全局范围内结束。
如果您需要从该范围内访问某些内容,您可以显式创建一个全局名称空间变量 iewindow.myApp = {}并将其附加到那里 iewindow.myApp.myMethod = function(){...}
传递window到 iife的原因是它在该范围内创建了一个本地引用。这将缩短查找链以获得更好的性能,并且变量也将是可缩小的。



In answer to your updated question:

回答您更新的问题:

To create a local ref to an element using this pattern you would supply it to the iife as an argument:

要使用此模式创建元素的本地引用,您可以将它作为参数提供给 iife:

(function(element){

    element.style.top = "100px";

})(document.getElementById("myId"));

...but i'm not sure that there is much value to using the pattern in this way? As per my comment, the thiskeyword is not affected and will still point to windowin this example.

...但我不确定以这种方式使用该模式有多大价值?根据我的评论,this关键字不受影响,window在本例中仍将指向该关键字。

I think that the thiskeyword is confusing you - it is not necessarily relevant to the iife pattern. Here is a good explanation of how its value is determined: http://net.tutsplus.com/tutorials/javascript-ajax/fully-understanding-the-this-keyword/

我认为this关键字让您感到困惑 - 它不一定与 iife 模式相关。这里有一个很好的解释它的价值是如何确定的:http: //net.tutsplus.com/tutorials/javascript-ajax/fully-understanding-the-this-keyword/

回答by i100

> it can be used for initializing? ... there is no getter available to fetch anything from it!

> 它可以用于初始化吗?...没有可用于从中获取任何内容的吸气剂!

yes it is often used for initialization and there is no need to fetch anything though it might.

是的,它经常用于初始化,尽管它可能不需要获取任何东西。

> The solution to above is to HAVE a return?

> 以上的解决方案是有回报?

no, it have not to have a return but again it might. If there is a return it will be past to whatever... i.e.

不,它不必有回报,但它可能会再次回报。如果有回报,它将成为过去......即

var a = (function(){})();

awill have whatever returned or undefined.

a将返回或未定义的任何内容。

(function(window, undefined){})(this);

(function(window, undefined){})(this);

parameter thiswill be the invoker - usually it is window , but might be any object. if you pass this as a parameter it will be accessible through the 1st argument ( window in the case).

参数this将是调用者 - 通常它是 window ,但也可能是任何对象。如果您将它作为参数传递,它将可以通过第一个参数(在这种情况下为 window )访问。

Hope the explanations are clear enough.

希望解释足够清楚。