我试图在Javascript中了解模块模式,并且遇到了各种不同的方法,我可以看到它。以下之间有什么区别(如果有的话):
Person = function() {
return {
//...
}
};
person1 = Person();
function Person2() {
return {
//...
}
}
person2 = Person2();
person3 = function() {
return {
//...
}
}();
person4 = (function() {
return {
// ...
}
})();
person5 = (function() {
return {
// ...
}
}());
他们似乎都对我做了同样的事情。
答案 0 :(得分:1)
// This creates a function, which then returns an object.
// Person1 isn't available until the assignment block runs.
Person = function() {
return {
//...
}
};
person1 = Person();
// Same thing, different way of phrasing it.
// There are sometimes advantages of the
// two methods, but in this context they are the same.
// Person2 is available at compile time.
function Person2() {
return {
//...
}
}
person2 = Person2();
// This is identical to 'person4'
// In *this* context, the parens aren't needed
// but serve as a tool for whoever reads the code.
// (In other contexts you do need them.)
person3 = function() {
return {
//...
}
}();
// This is a short cut to create a function and then execute it,
// removing the need for a temporary variable.
// This is called the IIFE (Immediate Invoked Function Expression)
person4 = (function() {
return {
// ...
}
})();
// Exactly the same as Person3 and Person4 -- Explained below.
person5 = (function() {
return {
// ...
}
}());
在上面的背景下,
所有人都做同样的事情。
我会把它们分解。
function() {}();
<functionExpression>(); // Call a function expression.
(<functionExpression>()); // Wrapping it up in extra parens means nothing.
// Nothing more than saying (((1))) + (((2)))
(<functionExpression>)();
// We already know the extra parens means nothing, so remove them and you get
<functionExpression>(); // Which is the same as case1
现在,所有这些都说==为什么你有时需要parens?
因为这是*函数声明)
function test() {};
为了制作函数表达式,你需要一些运算符。
(function test() {})
!function test() {}
+function test() {}
所有工作。
通过对parens进行标准化,我们能够:
答案 1 :(得分:0)
前两个不是模块模式,而是工厂函数 - 有一个Person
“构造函数”可以多次调用。有关语义差异,请参阅var functionName = function() {} vs function functionName() {}。
其他三个是IIFEs,它们完全相同。有关语法差异,请参阅Explain the encapsulated anonymous function syntax和Location of parenthesis for auto-executing anonymous JavaScript functions?。
答案 2 :(得分:0)