在一个'这个'中扩展2个班级。在javascript中

时间:2017-08-07 17:29:03

标签: javascript oop multiple-inheritance

我遇到了这个问题,我不知道如何从第三课扩展..所以我真的需要用参数' TYPE'来调用A类的方法,用C扩展,并且能够调用getType()with class C.任何解决方案?



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())




1 个答案:

答案 0 :(得分:0)



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())




相关问题