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中文網其他相關文章!