我想创建一个模块化类。它应该像下面的示例一样可用,并且应该可以分成文件。子类 (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 });
我只进行了以下工作。但因为我必须使用 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 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());
关于javascript - ES6类中类/模块类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45826909/