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

标签 javascript object key for-in-loop

所以我建立了一个系统,在该系统中,我的 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/

相关文章:

Javascript - 根据键字符串从对象动态获取子值

linux - ZSH 绑定(bind)键反向查找

r - 如何手动更改 ggplot2 中图例中的关键标签

javascript - 它继承自的字符串的原型(prototype)是什么?

javascript - 收到静态文件但在 django 中不起作用

javascript - 使用 javascript 添加换行符

Javascript - 错误...不是闭包内的函数

java - 处理照片上传的最佳方式是什么?

javascript - javascript对象中不熟悉的语法

javascript - 如何在数组 javascript 中添加带有 id 的新 key ?