如何使用(函数(全局){...})(this); [英] how to use (function(global) { ... })(this);

查看:98
本文介绍了如何使用(函数(全局){...})(this);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此主题中,我找到了一个我想要使用的JavaScript代码段。

In this thread I found a JavaScript code snippet which I want to use.

代码如下所示:

(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?

推荐答案

该函数会立即执行,您不会通过调用它来执行它。

The function is immediately executed, you do not execute it by calling it.

它是一个函数文字定义,后面跟着两个parens,它使该函数立即调用。阅读更多信息:立即调用函数表达式(IIFE)

It is a function literal definition, followed by two parens which causes that function to invoke immediately. Read more: Immediately-Invoked Function Expression (IIFE)

无论你放置在哪里的代码都马上运行。任何放置在调用parens中的东西都会作为参数传递给函数。假设你的示例代码是在全局范围内定义的,这个窗口对象,并且被引用为 global 在函数体中。这是封装程序以避免可变碰撞,强制严格模式等等的好方法。

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);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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