【问题标题】:Getting the name of an object in a for in loop to use as a key for another object在 for in 循环中获取对象的名称以用作另一个对象的键
【发布时间】:2015-02-21 04:16:26
【问题描述】:

所以我建立了一个系统,我的 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 作为 config 的键,其值为 GUI.input1(一个实际的 Input 对象)。 2. 焦点构造函数会以某种方式获取键名和值,并以我传递给它的相同名称存储它。现在它应该可以从 GUI 类中引用了。 3. 我将能够调用 GUI.focus.getfocus() 并返回对象 input1 或至少相同的名称。

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

【问题讨论】:

  • 这个解释不好什么是焦点角色?
  • 焦点的作用是接收一堆可能成为焦点的潜在对象,并将它们存储在它们都可引用的方式中。然后他们应该能够以我传递给他们的同名被召回。例如:GUI.focus.getfocus() 来返回 input1,因为它是焦点。

标签: javascript object key for-in-loop


【解决方案1】:

也许这就是你要找的东西:

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

【讨论】:

  • 谢谢,我没有想到有第二个对象作为任何键的值。谢谢,这肯定会奏效!
  • 我还有一个问题:为什么要使用prototype.x = fuction() 而不是将该函数放入类的声明中?说 this.x = fuction()?
  • 好吧,我不知道你的整个用例,但据我所知,你可以做 this.x = function... 但是将它作为原型有其好处 - 用于继承或枚举对象等。跨度>
猜你喜欢
  • 2016-02-11
  • 2017-07-02
  • 2013-11-13
  • 2018-09-02
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多