gpt4 book ai didi

javascript - 在 for in 循环中获取对象的名称以用作另一个对象的键

转载 作者:行者123 更新时间:2023-12-02 16:26:29 25 4
gpt4 key购买 nike

所以我建立了一个系统,在该系统中,我的 GUI 类在启动时会向 Focus 类构造函数发送一个配置对象。 GUI 类创建 Focus 类的实例,并且类构造函数有一个参数。我的代码:

var GUI = function(){
this.isWorking = "GUI(LOCAL) IS WORKING";

this.controlBox = new ControlBox();

this.input1 = new Input({
X: 350, Y: 50, SIZE: 50
});
this.input2 = new Input({
X: 350, Y: 125, SIZE: 50
});

this.focus = new Focus({
input1: this.input1,
input2: this.input2
});




this.drawGUI = function(){
// Draw the control box first?

//println("GLOBAL IS WORKING!");

this.controlBox.drawControlBox();
this.input1.drawInput(false);
this.input2.drawInput(false);

fill(255, 0, 0);
text("Global is working", 80, 25);

};

};

var Focus = function(config){

for(var focus in config){

}

this.getFocus = function(){
return;
};
};

在构造函数中使用此配置文件。我希望 Focus 类能够返回我在配置文件中发送的键名称。

这可能有点令人困惑,所以我将解释我希望它经历的过程: 1. 将 input1 作为配置的键,值为 GUI.input1 (实际的输入对象)。 2. 焦点构造函数将以某种方式获取键名称和值,并使用我传递给它的相同名称存储它。现在它应该可以从 GUI 类引用。 3. 我将能够调用 GUI.focus.getfocus() 并且它返回对象 input1 或至少返回相同的名称。

编辑:我想使用此配置参数的另一个原因是,当我想添加除了 input1 和 input2 之外的另一个焦点时,我可以将 objName: this.objName 放在其他焦点的正下方,而不是对每个焦点进行硬编码.

最佳答案

也许这就是您正在寻找的:

var Focus = function(config){
this.points = config || {};
this._focus = undefined;
};

Focus.prototype.add = function(point){
this.points[point.name] = point
};

/* or if you dont want the property name
Focus.prototype.add = function(id, point){
this.points[id] = point
};
*/

Focus.prototype.setFocus = function(focus){
this._focus = focus;
};

Focus.prototype.getFocus = function(focus){
return this.points[focus || this._focus];
};

// usage:
this.focus = new Focus({
input1 : { name : 'input1', point : this.input1 },
input2 : { name : 'input2', point : this.input2 }
});

this.focus.setFocus('input2');

this.focus.getFocus('input2');

关于javascript - 在 for in 循环中获取对象的名称以用作另一个对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28642017/

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