推杆;在函数定义的末尾 [英] Putting ; at the end of a function definition

查看:53
本文介绍了推杆;在函数定义的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么最好放一个;在函数定义的末尾.

例如

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆