什么是this
this
不是執(zhí)行上下文(EC才是執(zhí)行上下文)菠赚,this
是執(zhí)行主體
-
this
租副,在全局上下文下,this
指向window
- 塊級上下文中沒有自己的this僵腺,它的
this
是繼承所在上下文中的this
- 函數(shù)的私有上下文中鲤孵,
this
的情況會多種多樣
私有上下文中的this
- 事件綁定中,給元素的某個事件行為綁定方法辰如,當事件行為觸發(fā)普监,方法執(zhí)行,方法中的
this
是當前元素本身(特殊:IE6~8中基于attachEvent()方法實現(xiàn)的DOM2事件綁定,事件觸發(fā)凯正,方法中的this
是window
而不是元素本身)
let body = document.body
body.onclick = function () {
console.log(this) // body
}
body.addEventListener('click', function () {
console.log(this) // body
})
body.attachEvent('onclick', function () {
console.log(this) // window
})
- 普通方法執(zhí)行(包括自執(zhí)行函數(shù)執(zhí)行毙玻、普通函數(shù)執(zhí)行、對象成員訪問要調(diào)取方法執(zhí)行等)廊散,只需要看函數(shù)執(zhí)行的時候桑滩,方法名前面是否有“點”,有“點”允睹,“點”前面是誰运准,
this
就是誰,沒有“點”缭受,this
就是window
[非嚴格模式]/undefined
[嚴格模式]
let obj = {
fn: (function () {
console.log(this) // window
return function () {}
})()
}
function func () {
console.log(this)
}
let obj = {
func
}
func() // window
obj.func() // obj
[].slice() // 數(shù)組實例基于原型鏈機制胁澳,找到Array原型上的slice方法,然后再把slice方法執(zhí)行米者,此時slice方法中的this是當前的空數(shù)組
[].prototype.slice() // 此時this是Array.prototype
- 構(gòu)造函數(shù)執(zhí)行(
new
)韭畸,構(gòu)造函數(shù)體中的this
是當前類的實例。而原型上方法中的this
不一定都是實例塘雳,主要看執(zhí)行的時候陆盘,“點”前面的內(nèi)容(同第二點)
function Func () {
this.name = 'F'
console.log(this)
}
Func.prototype.getNum = function getNum () {
console.log(this)
}
let f = new Func() // Func {name: "F"}
f.getNum() // Func {name: "F"}
Func.prototype.getNum() // {getNum: ?, constructor: ?}
- ES6中提供了Arrow Function(箭頭函數(shù)):箭頭函數(shù)沒有自己的
this
,它的this
是繼承所在上下文中的this
let obj = {
func: function () {
console.log(this) // obj
},
sum: () => {
console.log(this) // window败明,塊級上下文中沒有自己的this
}
}
- 可以基于
call
/apply
/bind
方式隘马,強制手動改變函數(shù)中this
的指向