推杆;在函数定义的末尾 [英] Putting ; at the end of a function definition
问题描述
为什么最好放一个;在函数定义的末尾.
例如
var tony = function () {
console.log("hello there");
};
优于:
var tony = function () {
console.log("hello there");
}
TL; DR::如果没有分号,则函数表达式可以转换为立即调用的函数表达式,具体取决于其后的代码
自动分号插入是一种痛苦.您不应该依赖它:
var tony = function () {
console.log("hello there"); // Hint: this doesn't get executed;
};
(function() {
/* do nothing */
}());
对:
var tony = function () {
console.log("hello there"); // Hint: this gets executed
}
(function() {
/* do nothing */
}());
在第二个(错误的)示例中,不会插入分号,因为它后面的代码很有意义.因此,您期望分配给tony的匿名函数会立即与其他东西一起作为参数调用,而tony
被分配给您期望为tony
的返回值,这实际上不是您想要的.>
Why is it considered best practise to put a ; at the end of a function definition.
e.g.
var tony = function () {
console.log("hello there");
};
is better than:
var tony = function () {
console.log("hello there");
}
TL;DR: Without a semicolon, your function expression can turn into an Immediately Invoked Functional Expression depending on the code that follows it.
Automatic semicolon insertion is a pain. You shouldn't rely on it:
var tony = function () {
console.log("hello there"); // Hint: this doesn't get executed;
};
(function() {
/* do nothing */
}());
Versus:
var tony = function () {
console.log("hello there"); // Hint: this gets executed
}
(function() {
/* do nothing */
}());
In the second (bad) example, the semicolon doesn't get inserted because the code that follows it can make sense. So the anonymous function you expected to be assigned to tony gets called instantly with some other stuff as argument and tony
gets assigned to the return value of what you expected to be tony
, which is really not what you wanted.
这篇关于推杆;在函数定义的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!