【问题标题】:How to inject properties and methods of one class into another class?如何将一个类的属性和方法注入到另一个类中?
【发布时间】:2019-08-03 15:02:44
【问题描述】:

#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 类必须是一个独立的类,并且不应扩展任何一个类。

非常感谢任何帮助。

【问题讨论】:

  • 对不起,我评论后注意到您关于不扩展课程的评论。没关系!
  • 不用担心,谢谢。
  • 也许您需要重新考虑您的架构。
  • 是的,这很复杂,但我有点需要它以这种方式工作 -:

标签: javascript node.js


【解决方案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);

【讨论】:

  • 谢谢,但我已经尝试过这种方法。它确实注入了属性,但您不能调用 C 类中 A 类和 B 类的任何方法。
  • let b = new B(18); let c = b.getC(); console.log(c,c.getInfo());
  • 是的,该代码有效。但是另一个问题是在C类内部调用this.getAge()方法时,会抛出一个错误。
  • 哦,所以你想继承“方法”?希望这会有所帮助:developer.mozilla.org/en-US/docs/Web/JavaScript/…
猜你喜欢
  • 1970-01-01
  • 2012-04-14
  • 2021-04-01
  • 2014-11-14
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
相关资源
最近更新 更多