javascript - ES6类中类/模块类

标签 javascript node.js ecmascript-6 es6-class

我想创建一个模块化类。它应该像下面的示例一样可用,并且应该可以分成文件。子类 (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/

相关文章:

Internet Explorer 中的 JavaScript : How to do something after a variable is loaded/registered

javascript - 云函数: Crop image > Resize to multiple sizes

javascript - 未在 html 中定义的函数

node.js - 如何计算 Node 内 MongoDB 集合中的文档数量?

javascript - 在 cluster.on 上使用 babel 在 ES6 和 ES2016 之间的不同行为

javascript - 在通过标记数组映射之前,reactjs nullcheck

javascript - 使用 Flask 进行表单处理

javascript - Meteor.js Spiderable 和 Iron Router - 生产服务器上的光纤错误

node.js - Nodejs 在循环中等待

javascript - 关于let在ES6中充当全局变量时的问题