ES6中新增了箭頭函數這種語法,箭頭函數以其簡潔性和方便獲取this的特性。下面來總結一下他們之間的區別:app
普通函數下的this:函數
箭頭函數中的this:ui
function test() {
console.log(this);
}
test(); //window
複製代碼
test是一個全局函數,也就是掛載在window對象下的 test()等價於window.test();this
var obj = {
func: function () {
console.log(this);
setTimeout(function () {
console.log(this);
},0);
}
}
obj.func();
// obj,此時的this是obj對象
// window
複製代碼
say的宿主環境是obj,因此say裏面的this是obj。 定時器中的函數,因爲沒有默認的宿主對象,因此this指向window 嚴格模式下的this:spa
function test() {
'use strict';
console.log(this);
}
test();
//undefined
複製代碼
在嚴格模式下,沒有直接調用者的函數中的this是 undefinedcode
"use strict";
var obj={
say:function(){
console.log(this);
}
};
obj.say();
//obj
複製代碼
有直接調用者的this是它的調用者對象
var obj = {
say: function () {
setTimeout(() => {
console.log(this);
});
}
}
obj.say();
// obj
複製代碼
此時的 this繼承自obj, 指的是定義它的對象obj, 而不是 window繼承
var obj = {
say: function () {
var f1 = () => {
console.log(this); // obj
setTimeout(() => {
console.log(this); // obj
})
}
f1();
}
}
obj.say()
複製代碼
由於f1定義時所處的函數 中的 this是指的 obj, setTimeout中的箭頭函數this繼承自f1,因此無論有多層嵌套,都是 objit
var obj = {
say: function () {
var f1 = function () {
console.log(this);
setTimeout(() => {
console.log(this);
})
};
f1();
}
}
obj.say()
// window, f1調用時,沒有宿主對象,默認是window
// window
複製代碼
箭頭函數沒有this的綁定,必須經過查找做用鏈來決定其值。若是箭頭函數被非箭頭函數包含,則this綁定的是最近以層的非箭頭函數的this;不然。this的值會被設置爲undefined。 箭頭函數在定義的時候它所處的環境至關因而window, 因此在箭頭函數內部的this函數windowio