【问题标题】:Set Javascript Instance Variables programmatically以编程方式设置 Javascript 实例变量
【发布时间】:2012-06-28 00:01:21
【问题描述】:

我将获得一个对象数组,并希望在基于属性的类中设置实例变量。所以如果我得到这个:

ary = [{type: 'walrus', name: 'GorbyPuff'}, {type: 'humanoid', occupation: 'KingSlayer'}]

我想初始化一个对象,其中@walrus == ary[0]@humanoid == ary[1]

在 Ruby 中,我可以使用 instance_variable_set,但是如何在 Javascript 中实现呢?

【问题讨论】:

    标签: javascript metaprogramming instance-variables


    【解决方案1】:

    我不确定我是否能得到您想要实现的目标,但最简单的方法是:

    var theObj = {};
    for(var i=0;i<ary.length;i++)
    {
        theObj[ary[i].type] = ary[i];
    }
    

    这里担心的是,通过更改 ary 变量,您会无意中更改 theObj

    console.log(theObj.walrus.name);//Outputs: GorbyPuff
    ary[0].name = 'Nips!';
    console.log(theObj.walrus.name);//Outputs: Nips! <-- objects are passed by reference, always
    

    如果ary 变量是函数作用域的一部分,而结果对象是它的返回值,则不必担心。但是,如果两者都是全局范围的一部分(它们不应该这样做,这是不好的做法),这就会成为一个问题。

    因此我提出了这种方法:

    var obj = {};
    var i;
    while (ary.length !== 0)
    {
        i = ary.splice(0,1)[0];//removes element from array
        if (i.hasOwnProperty('type'))//always best to check the property you're going to use is there
        {
            obj[i.type] = i;
        }
    }
    

    【讨论】:

    • Javascript 通过引用传递所有对象,因此对 ary 中的对象所做的任何更改也将对它的任何引用进行。
    • 轰炸酱,完美。我是在构造函数中做的,所以结果是this[obj['type']] = obj 只要你确定它们是独一无二的,你就很好
    【解决方案2】:

    这是您想要的示例:

    // the class:
    function MyClass(){
      // stuff
    }
    
    // the data object
    var o = [
      {type:"MyClass",name:"a name"}
    ]
    
    // how to instantiate:
    var instances = [];
    for(var i=0;i<o.length;i++){
      if(typeof this[o[i].type] == "function")
        instances.push(new this[o[i].type](o[i].name))
    }
    

    如果在函数中创建类,则需要使用“this”作为对该函数的引用,否则可以使用“window”

    【讨论】:

      【解决方案3】:

      如果您想将该对象数组用作原型,您可以这样做:

      var Walrus = function(){};
      Walrus.prototype=ary[0];
      var aWalrus = new Walrus(); // creates a new Walrus.  aWalrus.name => GorbyPuff
      

      在 Javascript the Good Parts 中,Douglas Crawford 描述了一种更通用的方法:

      if (typeof Object.create !== 'function') {
         Object.create = function (o) {
            var F = function () {};
            F.prototype = o;
            return new F();
         };
      }
      

      你可以这样使用:

      var aWalrus = Object.create(ary[0]);
      

      【讨论】:

      • 好吧,就像您在回答中所说的那样,问题不清楚。我对它的解释不同。也许他只是想要 var x = ary[0]... 我不知道。看起来他可能不太了解 javascript 对象,所以这个答案可以很好地帮助他,即使它是题外话。
      • 另外,他说“根据属性在类中设置实例变量”,我将类解释为原型之类的东西。
      【解决方案4】:

      在 JS 中没有什么可以为你做到这一点,只需做一个循环来构建你想要的对象:

      ary = [{type: 'walrus', name: 'GorbyPuff'}, {type: 'humanoid', occupation: 'KingSlayer'}]
      instances={}
      for(x=0;x<ary.length;x++) instances[ary[x].type]=ary[x]
      
      document.write(instances.walrus.name) //GorbyBuff
      document.write(instances.humanoid.occupation) //KingSlayer
      

      【讨论】:

      • 我正在实例化一个类的实例,所以这些实例都属于同一类型
      猜你喜欢
      • 2012-09-14
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 2012-10-16
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多