我按照Stoyan Stefanov一书中的JavaScript模式而陷入困境......我无法继承原型。为什么?我做错了什么? (在NodeJS上运行此代码)
// inheritance
function Parent(name) {
this.name = name || 'some Name';
}
Parent.prototype.say = () => this.name;
function Child(name) {
// this.name = '123';
}
function inherit(C, P) {
C.prototype = new P();
}
inherit(Child, Parent);
debug(Child.prototype);
const kid = new Child();
debug(kid);
debug(kid.name);
debug(kid.say());
答案 0 :(得分:2)
箭头函数不能用作方法。 Parent.prototype.say
应该是正常的功能。来自MDN
箭头函数表达式的语法短于函数 表达式和没有自己的
this
,参数,超级或 new.target。这些函数表达式最适合非方法 函数,它们不能用作构造函数。
// inheritance
function Parent(name) {
this.name = name || 'some Name';
}
Parent.prototype.say = function() { // normal function
return this.name;
};
function Child(name) {
// this.name = '123';
}
function inherit(C, P) {
C.prototype = new P();
}
inherit(Child, Parent);
console.log(Child.prototype);
const kid = new Child();
console.log(kid);
console.log(kid.name);
console.log(kid.say());