如下面这段代码
class Animal {
sayName = () => {
console.log('I hate coding')
}
}
class Monkey extends Animal {
sayName() {
console.log('I love coding');
}
}
const monkey = new Monkey();
monkey.sayName();
为什么输出会是I hate coding
,但是如果Animal中的sayName是普通函数,输出就是I love coding
因为箭头函数的语法其实是



this.sayName = this.sayName.bind(this)
的语法糖。如果你写过class API 的
react
,可能会知道在之前的react
中,对于函数的绑定需要在constructor
中进行this.fn = this.fn.bind(this)
的上下文绑定.于是后来babel支持了这种箭头函数的快捷写法,实际上两种写法是等同的。而正常规范里的class方法是绑定在prototype上的,也就是ES5中Animal.prototype.sayName = function(){}
这样子的写法。如图所示,箭头函数sayName是绑定在实例上的,非箭头函数是在proto上的,这便是为什么输出是父类的log,你可以理解为箭头函数实际上是等同于先new一个对象之后再对该实例对象赋值方法