原文鏈接:(https://www.cnblogs.com/fanzhanxiang/p/8888963.html)
ES6中新增了箭頭函數(shù)這種語法,箭頭函數(shù)以其簡(jiǎn)潔性和方便獲取this的特性阀圾。下面來總結(jié)一下他們之間的區(qū)別:
普通函數(shù)下的this:
- 在普通函數(shù)中的this總是代表它的直接調(diào)用者挖炬,在默認(rèn)情況下荧库,this指的是window若贮,
- 在嚴(yán)格模式下,沒有直接調(diào)用者的函數(shù)中的this是 undefined使用
- call,apply,bind(ES5新增)綁定的,this指的是 綁定的對(duì)象
箭頭函數(shù)中的this:
- 箭頭函數(shù)沒有自己的this, 它的this是繼承而來; 默認(rèn)指向在定義它時(shí)所處的對(duì)象(宿主對(duì)象),
- 而不是執(zhí)行時(shí)的對(duì)象, 定義它的時(shí)候,可能環(huán)境是window,也有可能是其他的逸爵。
看下面這段代碼:
function a() {
console.log(this); //window
}
a();
因?yàn)閍是一個(gè)全局函數(shù)急鳄,也就是掛載在window對(duì)象下的扒披,所以a(),等價(jià)于window.a();
var obj = {
say: function () {
setTimeout(function () {
console.log(this); //window
});
}
}
obj.say();
定時(shí)器中的函數(shù)乐导,由于沒有默認(rèn)的宿主對(duì)象典阵,所以this指向window
var obj = {
func: function() {},
say: function () {
console.log(this);//obj,此時(shí)的this是obj對(duì)象
setTimeout(function () {
console.log(this); //window
that.func();
});
}
}
obj.say();
此時(shí)say的宿主環(huán)境是obj,所以say里面的this是obj,定時(shí)器中的函數(shù), 由于沒有默認(rèn)的宿主對(duì)象,所以默認(rèn)this指向window
嚴(yán)格模式下的this:
在嚴(yán)格模式下,沒有直接調(diào)用者的函數(shù)中的this是 undefined
var obj={
say:function(){
console.log(this); //obj
}
};
obj.say(); </pre>
有直接調(diào)用者的this是它的調(diào)用者
箭頭函數(shù)中的this:
var obj = {
say: function () {
setTimeout(() => {
console.log(this);// obj
});
}
}
obj.say(); </pre>
此時(shí)的 this繼承自obj, 指的是定義它的對(duì)象obj, 而不是 window!
var obj = {
say: function () { var f1 = () => {
console.log(this); // obj
setTimeout(() => {
console.log(this); // obj
})
}
f1();
}
}
obj.say() </pre>
因?yàn)閒1定義時(shí)所處的函數(shù) 中的 this是指的 obj, setTimeout中的箭頭函數(shù)this繼承自f1,所以不管有多層嵌套,都是 obj** </pre>
var obj = {
say: function () { var f1 = function () {
console.log(this); // window, f1調(diào)用時(shí),沒有宿主對(duì)象,默認(rèn)是window
setTimeout(() => {
console.log(this); // window
})
};
f1();
}
}
obj.say() </pre>
結(jié)果: 都是 window,因?yàn)?箭頭函數(shù)在定義的時(shí)候它所處的環(huán)境相當(dāng)于是window, 所以在箭頭函數(shù)內(nèi)部的this函數(shù)window