ECMAScript 之 Arrow Function 與 This
栏目: JavaScript · 发布时间: 7年前
内容简介:ES5 無論是 Function Declaration 或 Anonymous Function,都可以使用ECMAScript 2015一個常見的應用,在
ES5 無論是 Function Declaration 或 Anonymous Function,都可以使用 this 搭配 call() 、 apply() 與 bind() 動態改變 this ,ECMAScript 2015 更支援了 Arrow Function,這對原本的 this 、 call() 、 apply() 與 bind() 有任何影響嗎 ?
Version
ECMAScript 2015
Anonymous Function
const counter = {
count: 0,
increment() {
setInterval(function() {
console.log(++this.count);
}, 1000);
},
};
counter.increment();
一個常見的應用,在 counter object 定義 increment() method,在其內呼叫 setInterval() ,由於被要求傳入 function,因此以 Anonymous Function 傳入 setInterval() 。
由於 Anonymous Function 想對 counter property 做累加,很直覺的就寫出 ++this.count 。
- 但結果是
NaN
Why Not ?
setInterval(function() {
console.log(++this.count);
}, 1000);
對每個 function 而言,它都有自己的 this ,當 function 成為 object 的 method 時, this 就是 object,但 Anonymous Function 並非 object 的 method,因此 this 並不是指向 object。
這與 class-based OOP 的 this 永遠指向 object 不同,因為 ECMAScript 是以 function 為主體,所以 this 也是以 function 為考量,而非以 object 考量。
Self
const counter = {
count: 0,
increment() {
self = this;
setInterval(() => {
console.log(++self.count);
}, 1000);
},
};
counter.increment();
最傳統的解法,就是將用 self = this ,然後再利用 Closure 特性,讓 Anonymous Function 得到正確的 this 。
Function.prototype.bind()
const counter = {
count: 0,
increment() {
setInterval(function() {
console.log(++this.count);
}.bind(this), 1000);
},
};
counter.increment();
在 ES5 時代,若要解決這個問題,我們可以透過 bind() 強迫將 this 綁定進 Anonymous Function 的 this 。
Arrow Function
const counter = {
count: 0,
increment() {
setInterval(() => {
console.log(++this.count);
}, 1000);
},
};
counter.increment();
實務上 Lambda 最適合以 parameter 方式傳入 function,因此 ECMAScript 特別支援 Arrow Function 實現 Lambda,這比 Anonymous Function 可讀性更高。
在也由於 Arrow Function 在實務上常常要以 this 讀取 object 的 property,為了讓 Arrow Function 更好用,不必再使用 bind(this) ,Arrow Function 對於 this 有 2 項特色:
- Arrow Function 的
this將以 parent scope 的this為this - Arrow Function 的
this不能夠被改變,因此無法使用call()、apply()與bind()
Conclusion
- Arrow Function 並沒有要取代 Function Declaration 與 Anonymous Function
- 若
有使用call()、apply()與bind()改變this的需求,就要使用 Function Declaration 或 Anonymous Function - 若
沒有使用call()、apply()與bind()改變this的需求,就可使用 Arrow Function
Reference
Egghead.io , Understanding JavaScript’s this Keyword in Depth
以上所述就是小编给大家介绍的《ECMAScript 之 Arrow Function 與 This》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Realm of Racket
Matthias Felleisen、Conrad Barski M.D.、David Van Horn、Eight Students Northeastern University of / No Starch Press / 2013-6-25 / USD 39.95
Racket is the noble descendant of Lisp, a programming language renowned for its elegance and power. But while Racket retains the functional goodness of Lisp that makes programming purists drool, it wa......一起来看看 《Realm of Racket》 这本书的介绍吧!