示例
let a = {
name: 'A',
hehe: function () {
let f1 = function () {
console.log('f1', this)
}
let f2 = () => {
console.log('f2', this)
}
f1()
f2()
}
}
a.hehe()
// 輸出結果
// f1 window對象
// f2 a對象
class A {
constructor () {
this.name = 'A'
}
hehe () {
let f1 = function () {
console.log('f1', this)
}
let f2 = () => {
console.log('f2', this)
}
f1()
f2()
}
}
let a = new A()
a.hehe()
// 輸出結果
// f1 undefined
// f2 a對象
對于f2讯檐,由于是箭頭函數(shù)值桩,this相當于普通變量摆霉,本身沒有時向父級作用域獲取,因此獲取到對象a
對于f1,結果確實應該是undefined携栋,但由于代碼并未采用嚴格模式搭盾,因此輸出的應當是window對象。經(jīng)查閱MDN(https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes)婉支,class中默認采用嚴格模式鸯隅,因此即使我不顯示地聲明嚴格模式,f1中仍會輸出undefined
嚴格模式
類聲明和類表達式的主體都執(zhí)行在嚴格模式下向挖。比如蝌以,構造函數(shù),靜態(tài)方法何之,原型方法跟畅,getter和setter都在嚴格模式下執(zhí)行。