简体   繁体   English

为什么将javascript函数包装为匿名

[英]Why would a javascript function be wrapped as anonymous

In reading a technical education post I came across this sample code from the author..sterilized of course. 在阅读技术教育文章时,我偶然发现了作者的示例代码。当然。 The content of the functions is not what I found curious and everything worked as the author had described. 功能的内容不是我发现的好奇,一切都像作者描述的那样有效。

What caught me was wrapping the function in an anonymous (I think that's what they did) function. 抓住我的是将函数包装成匿名(我认为这就是他们所做的)功能。 The only thing I can see with my meager knowledge is that it creates a grouping/container. 我能用我微薄的知识看到的唯一一件事就是它创造了一个分组/容器。

Why is this and should I make a habit of this..I understand the second half may be subjective so disregard if too obtuse. 为什么这样,我应该养成这个习惯..我明白下半部分可能是主观的,所以如果太迟钝则无视。

(function ()
{
   FuncName1 = function (var1, var2, var3)
   {
       ....code n stuff....
   }

   FuncName2 = function (var1, var2)
   {
    .....code n stuff...
   }
 })();

Excellent explanations everyone. 每个人的优秀解释。 Thank You. 谢谢。 So my follow on question would be then shouldn't every function be wrapped? 那么我的后续问题是不应该包含所有功能? For example the author wrapped two functions in one "scope or module". 例如,作者在一个“范围或模块”中包含两个函数。 Couldn't those leak into each other? 那些不能相互泄漏吗?


So cookie monster to make the authors code even better I would do as such: 所以cookie怪物让作者代码更好我会这样做:

(function ()
{
   var FuncName1 = function (var1, var2, var3)
   {
       ....code n stuff....
   }

   var FuncName2 = function (var1, var2)
   {
    .....code n stuff...
   }
 })();

The key as you say in your comments is by using the keyword var keeps them in scope of the containing anonymous function. 您在评论中说的关键是使用关键字var将它们保存在包含匿名函数的范围内。 Not using var results in an implicit global scope. 不在隐式全局范围中使用var结果。

The anonymous function creates a scope. 匿名函数创建范围。 Any definitions inside the anonymous function will not "leak" outside and pollute the global namespace. 匿名函数内的任何定义都不会“泄漏”到外部并污染全局命名空间。 This lets you write more modular code. 这使您可以编写更多模块化代码。 When you do need to export something from inside the block into the global namespace, you can do so explicitly. 当您确实需要将块内部的内容导出到全局命名空间时,您可以明确地这样做。

Like the guys said above it creates modular code. 就像上面提到的那样,它创建了模块化代码。 If you set the anonymous function to return "things" and you set that to a variable you now have a closure that has name spaced goodness. 如果将匿名函数设置为返回“things”并将其设置为变量,则现在有一个名称间隔为goodness的闭包。

var name = (function() {

   var 
       lastName = 'Moody',
       firstName = Hank
   ;

   return {
      setName: function(newFirstName, newLastName) { 
                   firstName = newFirstName;
                   lastName = newLastName;
                },
      getName: function() { return firstName + " " + lastName; } 


    }

}());

Now you can get and set the code and it lives in it's own scope! 现在您可以获取并设置代码,它存在于自己的范围内! Bam - Modular Design Pattern. Bam - 模块化设计模式。

name.setName('Clark', 'Kent');
console.log(name.getName); // Will now output Clark Kent

Very powerful and simple design pattern. 非常强大而简单的设计模式。

Update: 更新:

Almost forgot the most important thing their name - IIFE or immediatetly invoked function expression! 几乎忘了他们的名字最重要的东西--IIFE或立即调用函数表达式!

"Because variables and functions defined within a function may only be accessed inside, but not outside, that context, invoking a function provides a very easy way to create privacy." “因为函数中定义的变量和函数只能在内部访问,而不能在外部访问,因此调用函数提供了一种非常简单的方法来创建隐私。”

http://benalman.com/news/2010/11/immediately-invoked-function-expression/ http://benalman.com/news/2010/11/immediately-invoked-function-expression/

This pattern is called 'Module' in Javascript, used for information hiding. 此模式在Javascript中称为“模块”,用于信息隐藏。

According to the book 'Javascript: The good part'. 根据书“Javascript:好的部分”。 The correct way of calling should be: 正确的呼叫方式应该是:

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

Not: 不:

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

Another method: 另一种方法:

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

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

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