首先要明白箭頭函數的作用:
箭頭函數除了讓函數的書寫變得很簡潔,可讀性很好外;最大的優點是解決了this執行環境所造成的一些問題。比如:解決了匿名函數this指向的問題(匿名函數的執行環境具有全局性),包括setTimeout和setInterval中使用this所造成的問題。
平時我們常見的window屬性和方法有alter,document,parseInt,setTimeout,setInterval,localtion等等,這些在默認的情況下是省略了window前綴的。(window.alter = alter).
ES5:
全局環境下,this 始終指向全局對象(window), 無論是否嚴格模式;
console.log(this.document=== document); // true // 在瀏覽器中,全局對象為 window 對象: console.log(this === window); // true this.name = 'zhangsan'; console.log(window.name); // zhangsan
函數上下文調用
函數直接調用
普通函數內部的this分兩種情況,嚴格模式和非嚴格模式。
非嚴格模式下,this 默認指向全局對象window
function f2(){ return this; } f2() === window; // true
而嚴格模式下, this為undefined
function f2(){ "use strict"; // 這里是嚴格模式 return this; } f2() === undefined; // true
ES6箭頭函數的this:
由於箭頭函數this是在定義函數時綁定的,不是在執行過程中綁定的,它會捕獲其所在(即定義的位置)上下文的this值, 作為自己的this值,
- 所以 call() / apply() / bind() 方法對於箭頭函數來說只是傳入參數,對它的 this 毫無影響。
- 考慮到 this 是詞法層面上的,嚴格模式中與 this 相關的規則都將被忽略。(可以忽略是否在嚴格模式下的影響)
一句話概括,es6箭頭函數里的this
指的是定義這個函數時外層代碼的this
,這句話可以從兩個方面理解:
- es6箭頭函數沒有自己的
this
- es6箭頭函數里的
this
是外層代碼(定義時,非執行時)this
的引用
例如:
var Animal = function() { this.name = "Animal1"; // 下面那一行的this指向的是這外面的this this.speak = (name,words) => { console.log(this.name + ' is saying ' + words + '.'); } } var cat = new Animal(); cat.speak(22,"miao ~"); // Animal is saying miao ~. var speak = cat.speak; speak(33,"miao ~");