1

オブジェクトの配列を取得し、プロパティに基づいてクラス内にインスタンス変数を設定したいと考えています。したがって、これを取得した場合:

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

オブジェクトを初期化したい場所@walrus == ary[0]@humanoid == ary[1]

Ruby では instance_variable_set を使用できましたが、これを Javascript でどのように実現できますか?

4

4 に答える 4

1

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-06-26T15:57:12.153 に答える
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;
    }
}
于 2012-06-26T15:58:28.120 に答える
0

オブジェクトの配列をプロトタイプとして使用する場合は、次のようにします。

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

Douglas Crawford は Javascript the Good Parts で、より一般的な方法について説明しています。

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

次のように使用できます。

var aWalrus = Object.create(ary[0]);
于 2012-06-26T16:03:44.450 に答える
0

ここにあなたが望むものの例があります:

// 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」を使用できます

于 2012-06-26T16:04:14.403 に答える