我想创建一个模块化的类。它应该像下面的示例一样可用,并且应该可拆分为文件。子类(Tasks)应该可以访问父类(Foo)的方法。

// Use basic methods
const foo = new Foo();
foo.connect();
foo.authenticate('user', 'password');

// Use task (or any other) module
const tasks = foo.Tasks;
tasks.createTask('ask on stackoverflow');
tasks.updateTask({ done: true });


我只有以下工作。但是因为必须使用Bar关键字启动new的新实例,所以无法访问更改后的this.output值。如何忽略new关键字,并使用与我上面所需语法相同的foo实例?



const Foo = class Foo {
  constructor() {
    this.output = 1;
  }

  changeOutput(output) {
    this.output = output;
  }
}

Foo.Bar = class Bar extends Foo {
  getOutput() {
    return this.output;
  }
}

const foo = new Foo();
foo.changeOutput(2);

const bar = new Foo.Bar(); // Creates a new instance what is wrong, but foo.Bar() or anything else doesn't work (Error: is not a function).
console.log(bar.getOutput()); // Result is 1, but should be 2

最佳答案

我仍然不知道您在寻找什么,但是似乎

遗产

class Foo {
  constructor() {
    this.output = 1;
  }
  changeOutput(output) {
    this.output = output;
  }
}

class Bar extends Foo {
  getOutput() {
    return this.output;
  }
}

const x = new Bar();
x.changeOutput(2);
console.log(x.getOutput());


要么

组成

class Foo {
  constructor() {
    this.output = 1;
    this.bar = new (new.target).Bar(this);
  }
  changeOutput(output) {
    this.output = output;
  }
}

Foo.Bar = class Bar {
  constructor(foo) {
    this.foo = foo;
  }
  getOutput() {
    return this.foo.output;
  }
}

const foo = new Foo();
foo.changeOutput(2);

const bar = foo.bar;
console.log(bar.getOutput());

09-16 18:17