ES6 JavaScript类

时间:2017-11-16 23:19:29

标签: javascript class oop ecmascript-6

有没有办法创建一个类,并且在该类中,构造函数方法传入来自其他类的两个不同对象,以及其他一些信息。例如,假设我有三个类,一个Statistics类,一个Attributes类和一个Character类。他们看起来像这样:

class Statistics {
    constructor(stren, dex, wis, cha, armorClass, hitPoints) {
        this._stren = stren;
        this._dex = dex;
        this._wis = wis;
        this._cha = cha;
        this._armorClass = armorClass;
        this._hitPoints = hitPoints;
    }
}

class Attributes {
    constructor(name, race, sex, level, height, weight, speed) {
        this._name = name;
        this._race = race;
        this._sex = sex;
        this._level = level;
        this._height = height;
        this._weight = weight;
        this._speed = speed;
    }
}

由于Character类的构造函数有13个以上的参数,我认为将它们分成其他类比编写带有13个以上参数的构造函数更好。那么有没有办法做类似的事情:

class Character {
    constructor(Statistics statistic, Attributes attributes) {
        .....
    }
}

编辑:不,这不是这个问题的重复,人们甚至在说问题重复之前是否真正阅读了被问到的内容?

1 个答案:

答案 0 :(得分:1)

请记住,类只是语法糖,因此您可以使用Character添加到Object.defineProperty原型并制作自己的getter。

编辑:用循环来干掉它。

class Statistics {
    constructor(stren, dex, wis, cha, armorClass, hitPoints) {
        this._stren = stren;
        this._dex = dex;
        this._wis = wis;
        this._cha = cha;
        this._armorClass = armorClass;
        this._hitPoints = hitPoints;
    }
}

class Attributes {
    constructor(name, race, sex, level, height, weight, speed) {
        this._name = name;
        this._race = race;
        this._sex = sex;
        this._level = level;
        this._height = height;
        this._weight = weight;
        this._speed = speed;
    }
}

class Character {
    constructor(statistics, attributes) {
        this.buildGetters(attributes)
        this.buildGetters(statistics)
      }
      
      buildGetters(obj) {
        for (let attr in obj){
          Object.defineProperty(Character.prototype, attr.replace("_", ""), {
            get: function() {
              return obj[attr]
            }
          })
        }
      }
}


const stats = new Statistics()
const attr = new Attributes("Mike")
const mike = new Character(stats, attr)
console.log(mike.name);