Node.js-在父级构造函数中定义子类的属性

时间:2019-01-09 10:21:30

标签: node.js inheritance configuration config settings

我正在使用OOP的超级功能-继承。因此,我有一堆具有相同属性的子类,但是此属性的值取决于类。我想将此属性的定义放入父级的构造函数中,但我不知道如何将值传递给它。

现在我正在使用npm-package config,但是拥有更多config-file的子类越多。因此,我想为每个孩子创建一个像child_*.yaml这样的文件,但是我无法弄清楚 如何导入必要的配置文件来正确定义孩子的属性< / em>

app.js (入口点):

const util = require('util');
const Factory = require('./src/factory');

console.log('\nInput child name (ex. \'child_one\') and press \'Enter\':\n');
process.stdin.on('data', function (data) {
  const input = data.toString().split('\n')[0];

  const child = Factory.createChild({child_name: input});
  console.log(`configuration: \n\t${util.inspect(child.configuration, null, 10)}`);
});

src / factory.js

const ChildOne = require('./children').child_one;
const ChildTwo = require('./children').child_two;
const ChildThree = require('./children').child_three;;

class Factory {
  static _supported_children (child_name) {
    switch (child_name) {
      case 'child_one':
        return ChildOne;
      case 'child_two':
        return ChildTwo;
      case 'child_three':
        return ChildThree;
      default:
        return ChildOne;
    }
  }

  static getConstructor (child_name = 'child_one') {
    return Factory._supported_children(child_name);
  }

  static createChild(data, ...args) {
    return new (Factory.getConstructor(data.child_name))(data, ...args);
  }
}

module.exports = Factory;

src / children.js

const Parent = require('./parent');

class ChildOne extends Parent {}
class ChildTwo extends Parent {}
class ChildThree extends Parent {}

module.exports = {
  child_one: ChildOne,
  child_two: ChildTwo,
  child_three: ChildThree,
};

src / parent.js

const settings = require('config');

const VALUES = settings.get('prop_s');

class Parent {
  constructor(data) {

    this.configuration = Object.assign({}, { prop: VALUES[data.child_name] });
  }
}
module.exports = Parent;

config / default.yaml

some_other_properties:
  property: '123'

prop_s:
  child_one:
    a: 1
    b: '2'
    c: 3
  child_two:
    d: 4
    e: 5
  child_three:
    f: '6'
    g: '7'
    h: '8'
    i: '9'

0 个答案:

没有答案