有没有办法创建一个类,并在该类中的构造函数方法从其他类传入两个不同的对象,以及一些其他信息。例如,假设我有三个类,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) {
.....
}
}
编辑:不,这不是那个问题的重复,人们在说问题是重复的之前是否真的阅读了所问的问题?
请记住,类只是语法糖,因此您可以添加到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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句