gpt4 book ai didi

javascript - 放;在函数定义的末尾

转载 作者:可可西里 更新时间:2023-11-01 01:45:26 26 4
gpt4 key购买 nike

为什么将 ; 放在最佳实践中?在函数定义的末尾。

例如

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,这真的不是你想要的。

关于javascript - 放;在函数定义的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20048093/

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