变量声明的语法? var a = (函数() { })()
我在一个网站上找到了下面的代码。
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
所以它遵循语法 var a = (blah balh..)()
它实际上意味着什么?像 a =()()
这样的变量声明是什么意思?
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I have found the following code in a website .
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
So it follows the syntax var a = (blah balh..)()
What does it actually mean? What is the meaning of variable declaration like a =()()
..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它定义一个一次性函数并立即执行它。您提供的代码被命名为模块模式——有关其属性的更多信息,请参见此处:http ://www.yuiblog.com/blog/2007/06/12/module-pattern/
一个普通的函数可能会像这样创建:
然后您可以像这样调用它:
但在您提供的示例中,该函数定义并执行一次,该函数返回一个具有两个函数的对象:incrementCounter 和resetCounter。您可以像这样调用它们:
testModule.incrementCounter()
和testModule.resetCounter()
当您有单个对象并且想要封装一些属性时,模块模式非常有用仅适用于闭包中定义的函数。
It's defining a single-use function and executing it immediately. The code you provided is named the Module Pattern -- see here for more information about its properties: http://www.yuiblog.com/blog/2007/06/12/module-pattern/
A normal function might be created like this:
And you could subsequently call it like so:
But in the example you provided, the function is both defined and executed once, and that function returns an object with two functions:
incrementCounter
andresetCounter
. You can call them like so:testModule.incrementCounter()
andtestModule.resetCounter()
The Module Pattern is useful when you have a single object and you want to encapsulate some properties which are only available to the functions defined in the closure.
执行匿名函数并将返回值赋给变量。
The anonymous function is executed and the return value is assigned to the variable.