【问题标题】:ES6 JavaScript classesES6 JavaScript 类
【发布时间】:2017-11-16 23:19:28
【问题描述】:

有没有一种方法可以创建一个类,并且在该类中,构造函数方法从其他类传入两个不同的对象,以及一些其他信息。例如,假设我有三个类,一个 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) {
        .....
    }
}

编辑:不,这不是那个问题的重复,人们在说问题重复之前是否真的阅读过所问的内容?

【问题讨论】:

  • 是和否 ... constructor(statistic, attributes) - 并检查两个参数是否属于构造函数中的正确类
  • 将这些新对象作为参数传递给Character 类有什么问题吗?就像没有“类型检查”的通用参数一样。
  • 您希望Character 获取统计信息/属性中的所有属性吗?如果是这样,这里有一个小提琴展示了如何做到这一点jsfiddle.net/fhnqh2og
  • 我想你刚刚描述了 Typescript。
  • @Mike 提问时你需要更清楚

标签: javascript class oop ecmascript-6


【解决方案1】:

请记住,类只是语法糖,因此您可以使用 Object.defineProperty 添加到 Character 原型并制作自己的 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);

【讨论】:

  • 你为什么不在Character类主体中写get name() { return this._attributes._name }Object.defineProperty 仅在您想动态创建具有不同名称的属性时才需要
  • 你能给我看看这方面的文档吗?我知道get 适用于 ES5 构造函数,但我的印象是它不适用于类语法。
  • 感谢您的回答!这就是我所追求的,我同意这样做 13 次会相当……耗时且占用大量空间。关于如何以更好的方式做到这一点的任何建议?
  • @Andrew get 适用于 ES5 对象字面量和 ES6 类。
  • @Mike Just Object.defineProperty 他们在属性名称字符串的循环中。
猜你喜欢
  • 2018-03-29
  • 2016-07-04
  • 2019-09-09
  • 2018-08-11
  • 2017-10-05
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
相关资源
最近更新 更多