简体   繁体   English

变量中的javascript匿名函数

[英]javascript anonymous function in variable

in the last few days i'm interesting in anonymous function in javascript , so i started to "explore" frameworks such as jquery , in the very first line i saw this piece of code : 最近几天,我对javascript中的匿名函数很感兴趣,因此我开始“探索”诸如jquery的框架,在第一行中,我看到了这段代码:

var jQuery = (function() { .. functions .. }();

and a question came in mind - what is the purpose of that code? 然后想到一个问题-该代码的目的是什么? why a variable contain anonymous function? 为什么一个变量包含匿名函数? what is the uses with that var? 该var有什么用? is it kind of function container or something? 是功能容器之类的东西吗? if it is how to access the functions? 如果是如何访问功能?

what is the purpose of that code? 该代码的目的是什么?

You are actually missing a closing parenthesis for this code to be valid javascript: 您实际上缺少使该代码有效的javascript的右括号:

var jQuery = (function() { ... })();

It defines an anonymous function and executes it immediately storing the result of it in the variable. 它定义了一个匿名函数并立即执行,将其结果存储在变量中。

You can think of it like this: 您可以这样想:

var jQuery = foo();

It's just that they didn't bother to define foo as an external function as they didn't need to call it elsewhere in the code. 只是他们不必费心将foo定义为外部函数,因为他们不需要在代码中的其他地方调用它。 So they defined it as an anonymous function. 因此,他们将其定义为匿名函数。

By doing this everything that is declared inside this anonymous function is scoped and accessible only to the containing anonymous function. 通过执行此操作,将对该匿名函数内部声明的所有内容进行范围划分,并且只能由包含的匿名函数访问。 It is not accessible to the outside. 外部无法访问。

通过减小该函数所有内容的作用域,可以防止在全局作用域中可能发生的冲突,意外吊起,并最大程度地减少附加到窗口对象的附加对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM