gpt4 book ai didi

closures - Javascript 模块模式和闭包

转载 作者:行者123 更新时间:2023-11-29 15:37:47 24 4
gpt4 key购买 nike

我正在尝试了解 Javascript 中的模块模式,并且遇到了各种不同的方式,我可以看到这样做。以下内容之间有什么区别(如果有的话):

Person = function() {
return {
//...
}
};
person1 = Person();

function Person2() {
return {
//...
}
}
person2 = Person2();


person3 = function() {
return {
//...
}
}();

person4 = (function() {
return {
// ...
}
})();

person5 = (function() {
return {
// ...
}
}());

他们似乎都对我做同样的事情。

最佳答案

// 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

现在,所有这些都说明了 == 为什么有时需要括号?

因为这是一个*函数语句)

function test() {};

为了构造一个函数表达式,你需要在它之前加上某种运算符。

(function test() {})
!function test() {}
+function test() {}

所有工作。

通过对括号进行标准化,我们能够:

  • 从 IIFE 中返回一个值
  • 使用一致的方式让代码的读者知道它是 IIFE,而不是常规函数。

关于closures - Javascript 模块模式和闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25325019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com