理解underscore.js代码的结构

tar*_*lah 6 javascript underscore.js

我在下划线源代码和许多其他开源JavaScript项目中看到了这种模式:

(function() {
 // the library code
}).call(this);
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释这种模式的作用?使用它有什么好处?

为什么不呢:

(function() {
 // the library code
}());
Run Code Online (Sandbox Code Playgroud)

chu*_*ckj 3

由于两者在正常情况下是等效的,因此我查看了源代码,并将其从您建议的形式更改为两年前的当前形式,并附有以下签入评论:

“添加了全局上下文的显式定义,以与 Adob​​e JS 兼容”

https://github.com/jashkenas/underscore/commit/aa916b8cfe565dc206d85c4cb74fbb6c499067a7

包含此更改的 Underscore 第一个版本的签入日志声称“改进了 Underscore 与 Adob​​e JS 引擎的兼容性,可用于编写 Illustrator、Photoshop 等脚本。”

http://underscorejs.org/ 版本 1.4.3

因此,做出此更改似乎是因为 Adob​​e 的 JavaScript 引擎当时不符合 ES3 或 ES5,但通过此更改,Underscore 与其变体兼容。

如果您不打算在 Adob​​e JS 中运行模块,那么您可以使用任一形式。如果您是,那么 Adob​​e JS 似乎需要 Underscore 使用的表单。