如何访问父对象的字段?解决JS对象方法this指向问题
解决方法:让mouth的sayName方法获取human的name
问题原因
调用human.mouth.sayName()时,函数里的this指向的是mouth对象(因为是通过mouth调用的方法),而mouth没有name属性,所以输出undefined。
几种可行的解决办法
直接引用外层的human变量
最简单的方式,直接在sayName里用human.name获取,缺点是如果human变量名后续修改,这里也要同步调整:const human = { name: "asdasd", mouth: { sayName(){ console.log(human.name) } } } human.mouth.sayName() // 输出 "asdasd"用箭头函数绑定外层this
箭头函数不会创建自己的this,它的this继承自定义时的外层作用域,这里外层作用域的this指向human:const human = { name: "asdasd", mouth: { sayName: () => { console.log(this.name) } } } human.mouth.sayName() // 输出 "asdasd"手动绑定this到human
用bind方法把sayName的this固定为human,这样不管怎么调用这个方法,this都指向human:const human = { name: "asdasd", mouth: { sayName(){ console.log(this.name) } } } // 绑定this human.mouth.sayName = human.mouth.sayName.bind(human) human.mouth.sayName() // 输出 "asdasd"通过闭包保留对human的引用
把mouth定义为立即执行函数,内部通过闭包拿到human的引用:const human = { name: "asdasd", mouth: (function() { const self = this return { sayName(){ console.log(self.name) } } }).call(human) } human.mouth.sayName() // 输出 "asdasd"
内容的提问来源于stack exchange,提问作者Andrey_buyback
相关产品推荐
相关产品推荐

