简体   繁体   English

未知的JavaScript语法可能与闭包有关

[英]Unknown JavaScript syntax might be related to closures

I found some JavaScript syntax which is unknown for me and I even don't know how it's called or what it does so I can't find any documentation. 我发现了一些我不知道的JavaScript语法,我什至不知道它的调用方式或作用,因此找不到任何文档。

I found it on MDC Doc Center : 我在MDC 文档中心找到了它:

var Counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }   
})();

The part I am interested in is: 我感兴趣的部分是:

var Counter = (function() {})();

What the round brackets do? 圆括号做什么? How this is called and where it can be used? 如何称呼它以及可以在哪里使用?

(function() {})() is an immediately executed function. (function() {})()是立即执行的功能。

This creates private scope around a block of code. 这将围绕代码块创建私有作用域。 This also can create a closure which can be useful to maintain state after the function ends. 这也可以创建一个闭包,对在函数结束后保持状态很有用。

You require () around function() {} because function() {}() is an illegal statement (the JS parser fails). 你需要()围绕function() {}因为function() {}()是非法的声明(JS的解析器失败)。

Also it is a habit to make sure you wrap an immediately executed function in () so that readers of your code are aware they should be interested in the return value of the function instead of the function. 还有一种习惯,就是确保将立即执行的函数包装在()以便代码阅读器知道他们应该对函数而不是函数的返回值感兴趣。

It's the module pattern. 这是模块模式。 It's usually used to create singletons. 通常用于创建单例。 See this answer: 看到这个答案:

What is this design pattern known as in JavaScript? 这种设计模式在JavaScript中称为什么?

Consider when you have a function called a: 考虑一下何时有一个称为a的函数:

function a() {
   alert("hi");
}

You call it like this: 您这样称呼它:

a();

In (function() {})() you're just skipping the part where you defined the function before-hand. (function() {})()您只是跳过了事先定义函数的部分。 In one fell swoop, you've defined an unnamed function and called it. 一口气,您定义了一个未命名的函数并将其调用。

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

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