首页 > 解决方案 > 当类的实例在 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

标签: javascriptperformanceclasssemantics

解决方案


您可以耦合函数及其属性。

所以像:

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());

推荐阅读