创建模块的常见做法是将它们包装在括号中,这样就不会泄漏模块外部的任何变量(当连接等时)。
还有void
运算符,计算给定表达式并返回undefined
。 (参见MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void%20MDN)
我想知道为什么更喜欢将函数包装在括号中而不是使用void
。它是历史的吗,是否与串联有关,或者其他?
我知道当其中一个文件缺少分号时,您可能会遇到串联问题,从而导致严重的问题,直到您注意到为止。
Examples
比如说 module1.js (注意缺少逗号):
(function () {
return function () {
console.log('module1. I should not be called');
};
})()
并且,module2.js:
(function () {
return function () {
console.log('module2. I should not be called either');
};
})();
如果将这些脚本连接到一个包中,它将生成以下内容:
(function () {
return function () {
console.log('module1. I should not be called');
};
})()(function () {
return function () {
console.log('module2. I should not be called either');
};
})();
由于两个模块(文件)都返回一个函数,因此第二个所谓的 IIFE 变成了对第一个模块的返回值,有效调用console.log
。常见的解决方法是声明您的模块!(function (){})();
这强制返回值是布尔值。
但是,如果您要使用void
, like:
void function () {
return function () {
console.log('module1. I should not be called');
};
}()
连接的文件仍然是错误的,但您会在第一次运行时注意到错误,因此更容易注意到。见下文。
void function () {
return function () {
console.log('module1. I should not be called');
};
}()void function () {
return function () {
console.log('module2. I should not be called either');
};
});
这会抛出Unexpected token void
。就模块而言,我相信!(function(){}()
and void function(){}()
达到同样的效果。但我觉得void
看起来比用参数和前置来包装函数更干净(主观)!
to it.
我错过了什么?如果我们使用的话不是更好吗void
?