【发布时间】: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