function funcName(params) { return params + 2; } funcName(2); // 4
var funcName = (params) => params + 2 funcName(2); // 4
() => { statements }
parameters => { statements }
parameters => expression // 等价于: function (parameters){ return expression; }
var double = num => num * 2
double(2); // 4 double(3); // 6
function Counter() { this.num = 0; } var a = new Counter();
console.log(a.num); // 0
function Counter() { this.num = 0; this.timer = setInterval(function add() { this.num++; console.log(this.num); }, 1000); }
var b = new Counter(); // NaN // NaN // NaN // ..
clearInterval(b.timer);
function Counter() { this.num = 0; this.timer = setInterval(function add() { console.log(this); }, 1000); } var b = new Counter();
clearInterval(b.timer);
function Counter() { this.num = 0; this.timer = setInterval(() => { this.num++; console.log(this.num); }, 1000); } var b = new Counter(); // 1 // 2 // 3 // ...
function Counter() { var that = this; this.timer = setInterval(() => { console.log(this === that); }, 1000); } var b = new Counter(); // true // true // ...
clearInterval(b.timer);
箭头函数写代码拥有更加简洁的语法;
不会绑定this。
以上是JavaScript箭头函数的用法介绍的详细内容。更多信息请关注PHP中文网其他相关文章!