class 中的 ES6 class / 模块化 class

ES6 class in class / modular class

我想创建一个模块class。它应该像下面的示例一样可用,并且应该可以分离到文件中。子 class (Tasks) 应该可以访问父 class (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 Whosebug');
tasks.updateTask({ done: true });

我只得到以下工作。但是因为我必须使用 new 关键字启动 Bar 的新实例,所以我无法访问 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 foo = new Foo();
foo.changeOutput(2);

const bar = new Bar(); 
bar.changeOutput(2);

console.log(bar.getOutput()); //

当您创建子实例时,Bar 将调用 Foo 的构造函数并将输出的值初始化为 1。当您调用 getOutput 方法时,它将更改 bar 的输出值。

我从未见过任何面向对象的语言以您尝试的方式工作,javascript。

Foo.Bar 是 Foo 上的静态方法,它扩展了 class Foo,而不是实例 foo。这就是为什么你会出现数字 1。

分离您的顾虑,并将更改应用于您正在使用的实例,即具有任务的实例。

class Bar extends Foo {
  getOutput() {
    return this.output;
  }
}
var bar = new Bar();
bar.changeOutput(2)
bar.getOutput() //2

但是..

您可以编辑 this 的绑定来实现您想要的,但是首先遵循糟糕的 OOP 设计模式并不是一个好的做法(您可以实现您想要的通过其他范例或将两个 classes 合并在一起)。

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

console.log(bar.getOutput.call(foo)); // Result is 2 now

我还是不知道你在找什么,不过好像是

继承

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