投入; 在函数定义的末尾

Mor*_*ive 13 javascript jslint

为什么认为最好的做法是 在函数定义的末尾.

例如

var tony = function () {
   console.log("hello there");
};
Run Code Online (Sandbox Code Playgroud)

比以下更好:

var tony = function () {
   console.log("hello there");
}
Run Code Online (Sandbox Code Playgroud)

Tib*_*bos 35

TL; DR:没有分号,您的函数表达式可以转换为立即调用的函数表达式,具体取决于它后面的代码.


自动分号插入是一种痛苦.你不应该依赖它:

var tony = function () {
   console.log("hello there"); // Hint: this doesn't get executed;
};
(function() {
  /* do nothing */
}());
Run Code Online (Sandbox Code Playgroud)

与:

var tony = function () {
   console.log("hello there"); // Hint: this gets executed
}
(function() {
  /* do nothing */
}());
Run Code Online (Sandbox Code Playgroud)

在第二个(坏)示例中,分号未插入,因为其后面的代码可能有意义.因此,您希望分配给tony的匿名函数会立即被其他一些东西作为参数调用,tony并被分配给您期望的返回值tony,这实际上不是您想要的.


Thi*_*ter 8

你发布了一个函数表达式.与块不同,语句以分号结束,因此您应该在那里插入分号,而不是依赖ASI来隐式执行.

不添加分号可能会导致意外行为,具体取决于后面的代码.