为什么许多javascript库以“(function(){"? [英] Why do many javascript libraries begin with "(function () {"?

查看:102
本文介绍了为什么许多javascript库以“(function(){"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么许多javascript库看起来像这样:

Why do many javascript libraries look like this:

(function () { 
    /* code goes here */ 
})();

它似乎定义了一个立即调用的未命名函数。为什么要付出这些努力?

It appears to define an unnamed function which is immediately called. Why go through this effort?

推荐答案

这是在JavaScript中执行命名空间的标准方法。如果您只是声明

This is standard way to do namespacing in JavaScript. If you just declare

var my_cool_variable = 5;

它将是全局的,并且可能与使用相同变量的其他库冲突。

it will be global and might conflict with other libraries, that use the same variable.

但是,如果你这样做

(function() {
    var my_cool_variable = 5;
})();

它现在是匿名函数的局部变量,在该函数范围之外是不可见的。您仍然可以通过在变量前面声明 var 来公开可访问的API,这样它将是全局的,但现在您可以选择。

it is now local variable for anonymous function and is not visible outside of the scope of that function. You still can expose accessible API by not stating var in front of variable, that way it will be global but now you have a choice.

这篇关于为什么许多javascript库以“(function(){"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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