如何将一类的属性和方法注入另一类?

时间:2019-03-13 02:16:07

标签: javascript node.js

#javascript #nodejs

我的脚本中有3个类(A,B,C)。 B类扩展了A类,而B类内部则是一种调用C类新实例的方法。

示例代码:

// First class
class A {
    constructor() {
        this.name = 'Eve';
    }

    getName() {
        return this.name;
    }
}

class B extends A {
    constructor(age) {
        this.age = age;
    }

    getAge() {
        return this.age;
    }

    getC() {
        // This is where I needed a solution
        return new C();
    }
}

class C {
    constructor() {
        this.address = 'Market Village';
    }

    getAllInfo() {
        return this;
    }
}

如果运行以下代码,则预期输出应为:

let b = new B(18);
let info = b.getC().getInfo();
console.log(info); // {address: 'Market Village'}

但是我想让类C继承类A和B的所有属性和方法,以便类C能够使用两个类的属性和方法。

我尝试了几种方法,但是没有用。

尝试1:

此方法将类A和B的所有属性和方法注入到类C中,但问题是它抛出一个错误,提示cannot set ... of undefined,由于某种原因,类C的方法未读取:

getC() {
    C.calls(this);
}
尝试#2

此方法读取C类的所有方法,并注入A类和B类的所有属性,但不注入其方法。同样,当您在类C中调用类A和B的任何方法时,都会引发错误:

getC() {
    let _classC = new C();
    Object.assign( _classC, this );

    return _classC;
}

有没有办法调用类C的新实例并注入类B和A的所有属性和方法?

请注意,C类必须是独立的类,并且不能扩展这两个类。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

希望这会有所帮助:

class A {
    constructor() {
        this.name = 'Eve';
    }

    getName() {
        return this.name;
    }
}

class B extends A {
    constructor(age) {
        super();
        this.age = age;
    }

    getAge() {
        return this.age;
    }

    getC() {
        let _classC = new C();
        Object.assign( _classC, this );

        return _classC;
    }
}

class C {
    constructor() {
        this.address = 'Market Village';
    }

    getInfo() {
        return this;
    }
}
let b = new B(18);
let info = b.getC().getInfo();
console.log(info);
相关问题