前言
箭頭函數(shù)極大地簡化了this的取值規(guī)則。
普通函數(shù)與箭頭函數(shù)
普通函數(shù)指的是用function定義的函數(shù):
var hello = function () {console.log("Hello, Fundebug!");}箭頭函數(shù)指的是用=>定義的函數(shù):
var hello = () => {console.log("Hello, Fundebug!");}JavaScript箭頭函數(shù)與普通函數(shù)不只是寫法上的區(qū)別,它們還有一些微妙的不同點,其中一個不同點就是this。
箭頭函數(shù)沒有自己的this值,箭頭函數(shù)中所使用的this來自于函數(shù)作用域鏈。
這句話很簡單,不過聽著稍微有點莫名其妙,得從頭說起。
this到底是什么?
關于this的文章也夠多了,有時候越描越黑,我就不再添亂了,我只負責搬運一下MDN文檔:this,感興趣的可以仔細閱讀一下,我摘錄一些最重要的話就好了。
A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
JavaScript是一門比較奇特的語言,它的this與其他語言不一樣,并且它的取值還取決于代碼是否為嚴格模式("use strict")。
this的值是什么?
The JavaScript context object in which the current code is executing.
this就是代碼執(zhí)行時當前的context object。
Global context
In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.
代碼沒有在任何函數(shù)中執(zhí)行,而是在全局作用域中執(zhí)行時,this的值就是global對象,對于瀏覽器來說,this就是window。
這一條規(guī)則還是比較容易接受的。
Function context
Inside a function, the value of this depends on how the function is called.
函數(shù)中的this值取決于這個函數(shù)是怎樣被調(diào)用的,這一條規(guī)則就有點變態(tài)了,也是很容易出BUG的地方。
另外,this的值還與函數(shù)是否為嚴格模式("use strict")有關,這就非常的喪心病狂了...
大家如果好奇的話,出門左轉(zhuǎn)看MDN文檔,我多說無益,只說明一種簡單的情況。
As an object method
When a function is called as a method of an object, its this is set to the object the method is called on.
當函數(shù)作為對象的方法被調(diào)用時,它的this值就是該對象。
var circle = {radius: 10,getRadius() {console.log(this.radius);}};circle.getRadius(); // 打印 10self = this?
當我們需要在對象方法中嵌套一個內(nèi)層函數(shù)時,this就會給我們帶來實際的困擾了,大家應該寫過這樣的代碼:
新聞熱點
疑難解答
圖片精選