var name = "out"
let outerObj = {
name: "outerObj",
testFunc() {
let obj = {
name: "obj",
test: {
name: "innerObj",
visualAge: this.name,
getVisualAge1: (function () {
return this.name
})(),
getVisualAge2: function () {
return this.name
},
getVisualAge3: () => {
return this.name
},
getVisualAge4: (() => {
return this.name
})(),
}
}
console.log(obj.test.visualAge) //outerObj
// visualAge指向总对象的外一层(相当于上一层作用域链的this) !!
console.log(obj.test.getVisualAge1) //out
// 匿名function函数指向Window
console.log(obj.test.getVisualAge2()) //innerObj
// 方法指向调用对象的最近一层
console.log(obj.test.getVisualAge3()) //outerObj
// 对象内箭头函数指向总对象的外一层(相当于上一层作用域链的this) !!
console.log(obj.test.getVisualAge4) //outerObj
// 匿名箭头函数指向同箭头函数
}
}
outerObj.testFunc()
总结: 对象和箭头函数自身没有this,指向上层作用域链
自执行匿名function函数指向window
对象方法指向调用对象的最近一层
评论(0)