javascript - 当类的实例在 js 中需要不同的函数和变量时,有什么更好的方法?
问题描述
我有一个名为的类Gamer
,它的每个实例都需要不同的逻辑。所以Gamer
得到一个函数作为参数,但是这个函数需要新的属性(处理自定义函数操作)。那么考虑性能/语义会更好:只需添加这些变量gamerInstance.new_attr = ...
或为每个扩展类的实例创建一个新Gamer
类?或者我不知道的另一件事......请记住,在某些情况下可能Gamer
不需要额外的属性。
这个函数作为参数调用array.length(>超过10^6)次
class Gamer{
#name;
#function;
constructor(name, function){
this.#name = name;
this.#function = function;
this.number = 0;
}
static get SOME_CONST() { return 5; }
//called many times
manageStrategy(index){ this.#strategy(this, index); }
}
let gamer1 = new Gamer("Gary", (gamer, index) => {
//do some thing to gamer.number
});
let gamer2 = new Gamer("John", (gamer, index) => {
//do another thing to gamer.number
});
gamer1.new_attr = 0;
gamer1.new_attr2 = [];
//gamer2 doesn't need extra data to handle its function logic
解决方案
您可以耦合函数及其属性。
所以像:
class GamerLogicA {
propA;
propB;
propC;
init(){ /*doSomething with propA, propB, propC*/ }
}
class GamerLogicB {
propD;
propE;
init(){ /*doSomething with propD, propE*/ }
}
class Gamer{
#name;
#logic;
constructor(name, logic){
this.#name = name;
this.#logic = logic;
this.#logic.init();
}
}
然后你只需注入它:
let g1 = new Gamer('Gary', new GamerLogicA())
let g2 = new Gamer('John', new GamerLogicB());
推荐阅读
- mysql - 不允许大于 max_allowed_packet 的数据包
- java - 为什么 numberpicker.getvalue() 没有得到返回值?
- r - 无法将数据从 R 导出到 Vertica
- python - 在 python 中单独为特定数据类型执行任务
- c# - 在 datetimepicker c# 中读取自定义格式
- android - 从 KOTLIN 的图库中选择多个图像(想要图像路径)
- javascript - jquery daterange选择器在选择日期之前选择结束日期丢失结束日期选择
- amazon-web-services - 从 localhost 通过 HTTPS 访问 AWS ALB
- docker - 如何结合docker和sklearn
- django - 基于函数的视图中的 Ajax