javascript 如何使用 (function(global) { ... })(this);
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10314891/
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
how to use (function(global) { ... })(this);
提问by BetaRide
In this threadI found a JavaScript code snippet which I want to use.
在这个线程中,我找到了一个我想使用的 JavaScript 代码片段。
The code looks like:
代码如下:
(function(global) {
// the function code comes here
})(this);
How can i call this function to execute the code? What do I have to pass in for this global
variable?
我怎样才能调用这个函数来执行代码?我必须为这个global
变量传递什么?
回答by JAAulde
The function is immediately executed, you do not execute it by calling it.
该函数会立即执行,您不会通过调用它来执行它。
It is a function literal definition, followed by two parens which causes that function to invoke immediately. Read more: Immediately-Invoked Function Expression (IIFE)
它是一个函数字面定义,后跟两个括号,使该函数立即调用。阅读更多:立即调用函数表达式 (IIFE)
Whatever code you place inside is run right away. Anything placed in the invocation parens is passed into the function as an argument. Assuming your sample code was defined in the global scope, this
is the window
object, and is referenced as global
within the function body. It is a great way to encapsulate your programs to avoid variable collision, force strict mode, and much more.
您放置在其中的任何代码都会立即运行。调用括号中的任何内容都作为参数传递到函数中。假设您的示例代码是在全局范围内定义的,this
是window
对象,并且global
在函数体内被引用。这是封装程序以避免变量冲突、强制严格模式等的好方法。
回答by Jon
This construct defines a function:
这个构造定义了一个函数:
function(global) {
// the function code comes here
}
and immediately calls it, passing this
as a parameter:
并立即调用它,this
作为参数传递:
([function])(this)
The identifier global
is simply the name of this parameter inside the function body. For example, try
标识符global
只是函数体内此参数的名称。例如,尝试
console.log(this); // outputs something
(function(global) {
console.log(global); // outputs the same thing as above
})(this);
回答by Quentin
How can i call this function to execute the code?
我怎样才能调用这个函数来执行代码?
It is already being called: (this)
它已经被调用: (this)
What do I have to pass in for this global variable?
我必须为这个全局变量传递什么?
this
this