【发布时间】:2018-04-29 07:08:29
【问题描述】:
以下函数声明格式有什么区别? 什么时候用哪个更正确?
从初学者的角度和高层次(非深度)的角度来看,它们三者的工作方式似乎相同 - 因此它会让人感到困惑并提出问题。
1.
const counter1 = function(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
2.
function counter2(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
3.
const counter3 = (num) => {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
他们都看起来表现相同。
【问题讨论】:
-
与 1. 相比,3. 具有箭头函数提供的附加限制/功能:箭头函数没有自己的 @987654324 @、
arguments、super或new.target。 -
总是使用 #2 来获得提升。它也是最短的。
标签: javascript node.js function-declaration