代码如下
class Person{
constructor(name){
this.name = name
}
}
Object.assign(Person.prototype, {
getName: ()=>{
return this.name
}
})
const me = new Person('Yokiijay')
console.log( me.getName() ) // => undefined
问题如下
由于箭头函数的this继承自上一层对象的this
而function的this是当前调用自己的对象的this
所以
这里用箭头函数并拿不到 Person对象下的name属性
请问
那么如何把箭头函数的this指向改为function的this指向呢?call?bind?apply?
正确应该是不用箭头函数,箭头函数不产生this,它的this在定时就确定了,所以它有它使用的限定区域,并非万能。