js中箭头函数如何改回this指向?

代码如下

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?

阅读 8.1k
4 个回答

正确应该是不用箭头函数,箭头函数不产生this,它的this在定时就确定了,所以它有它使用的限定区域,并非万能。

箭头函数一旦定义完毕,this 就没有办法改变了,call,bind 都不管用。

箭头函数声明的时候context就已经决定了

提供思路哦,看到这个需求之后我开始想:

  1. 我在想出现问题肯定是this
  2. this都分别指向谁呢?打印一下
  3. 那修改this的指向用什么呢?穿透法、call/apply/bind

结果第1、2步我发现,第一个this指向了Person,第二个this指向了全局
那要么都指向全局、要么都指向Person,so...穿透法最简单,如下代码:喜欢的话给洒家采纳一下

var _this = this
class Person{
    constructor(name){
        _this.name = name
    }
}
Object.assign(Person.prototype, {
    getName: ()=>{
        return this.name
    }
})

const me = new Person('Yokiijay')
console.log( me.getName() )
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题