在javascript中的'this'的一个类中扩展2个类
问题描述:
我遇到了这个问题,我不知道如何从第三个类扩展..所以我真的需要用参数'TYPE'调用A类的方法,extend与C,并能够与类C调用getType()。任何解决方案?在javascript中的'this'的一个类中扩展2个类
const TYPE = 'TYPE'
class A {
constructor(type) {
this.type = type;
}
getType() {
return this.type;
}
}
class B {
constructor(id) {
this.id = id;
}
getId() {
return this.id;
}
}
class C extends B {
constructor(id) {
super(id);
//Here should be a function that should bind the method from class A
}
}
const c = new C(1);
console.log(c.getId())
console.log(c.getType())
答
const TYPE = 'TYPE'
class A {
constructor(type) {
this.type = type;
}
getType() {
return this.type;
}
extend(extendedClassInstance){
extendedClassInstance.type = this.type;
extendedClassInstance.getType = this.getType.bind(extendedClassInstance)
}
}
class B {
constructor(id) {
this.id = id;
}
getId() {
return this.id;
}
}
class C extends B {
constructor(id) {
super(id);
(new A(TYPE)).extend(this)
}
}
const c = new C(1);
console.log(c.getId())
console.log(c.getType())
+0
请勿使用'.bind(extendedClassInstance)'。 – Bergi
为什么不能有'B类扩展A'?或者你真的问过如何从'C'中的'A'和'B'继承? – Bergi
在javascript中,当你执行'extend'时,基本上你正在做的是'原型继承'。由于你的基础对象只能有一个原型,你不能做多重继承。你可以做的一件事是你的B类可以扩展A类,所以间接地你的C类将会扩展这两个类。 –
'Object.assign(this,A.prototype)'可以去你的评论的地方。 – 4castle