为什么在JavaScript类中,箭头函数优先于函数声明?
例子 :
class Parent {
work = () => {
console.log('This is work() on the Parent class');
}
}
class Child extends Parent {
work() {
console.log("This is work() on the Child class ");
}
}
const kid = new Child();
kid.work();
在这个例子中,parent work()方法会发生火灾。
"这是父类上的work()"
我只是想了解 为什么 在JS类中,箭头函数总是优先于函数声明,尤其是在继承和多态方面。
这与作为一个箭头函数无关。它是优先的,因为它是一个 班级领域. 类字段被添加为 自己 属性,而方法被添加到 Child.prototype.work
. 即使你把它从箭头函数改为普通函数,它仍然会执行类字段。
当你访问 kid.work
财产的查看顺序是
kid
对象Child.prototype.work
Parent.prototype.work
Object.prototype
class Parent {
// doesn't matter if it an arrow function or not
// prop = <something> is a class field
work = function() {
console.log('This is work() on the Parent class');
}
}
class Child extends Parent {
// this goes on Child.prototype not on the instance of Child
work() {
console.log("This is work() on the Child class ");
}
}
const kid = new Child();
// true
console.log( kid.hasOwnProperty("work") )
// true
console.log( Child.prototype.hasOwnProperty("work") )
// false
// because work inside Parent is added to each instance
console.log( Parent.prototype.hasOwnProperty("work") )
kid.work();
// How to force the Child method
Child.prototype.work.call(kid)