gpt4 book ai didi

javascript - ES6 JavaScript 类

转载 作者:行者123 更新时间:2023-12-03 03:01:59 26 4
gpt4 key购买 nike

有没有一种方法可以创建一个类,并在该类的构造函数方法中传递来自其他类的两个不同的对象以及一些其他信息。例如,假设我有三个类,一个统计类、一个属性类和一个字符类。它们看起来有点像这样:

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) {
.....
}
}

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

最佳答案

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

关于javascript - ES6 JavaScript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340806/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com