2016-10-07 4 views
0

ネストされたオブジェクトクラスをループし、そのオブジェクトのプロパティを抽出する必要があります。しかし、オブジェクト内部からプロパティ値を変更しても、これらのオブジェクトのルートオブジェクトを保持する変数の値は変更されません。オブジェクトの内部からチェックすると、新しい値が正しく適用されます。JavaScriptはすべてのオブジェクト参照のプロパティ変更を反映します

ただし、既存のプロパティを変更する代わりに新しいプロパティを追加すると、新しいプロパティにアクセスできます。

js fiddle

var OO = function(o, parent){ 
     this.parent = parent || null; 
     this.init(o); 
     return this; 
    }; 

    OO.prototype = { 
     init: function(o){ 
      this.obj = typeof o === 'object' ? new OO(o.name, this) : o; 
      this.type = typeof o === 'object' ? 'object' : 'string'; 

      if(typeof o === 'string'){ 
       this.change(); 
       console.log(this.parent); // Here top-level oo object holds values called in change() function. I want the variable (oo_var) holding this top-level oo to have same property values too. 
       this.add(); 
      }    
     }, 

     change: function(){ 
      this.parent.obj = 'Orange'; // Holds {} before changing 
      this.parent.type = 'string'; // 'object' before changing 
     }, 

     add: function(){ 
      this.parent.another_obj = 'Another'; 
      this.parent.another_type = 'another string'; 
     } 
    }; 

    var oo_var = new OO({name: 'Apple'}); // This var doesn't refresh the obj & type property values applied in change() function. But has properties added in add() function. 

Iは、各レベルの兄弟とオブジェクトネスト多くのレベルを有します。

+0

を子オブジェクトの作成 - そしてそれらを '.change()'した後。 – Bergi

+0

本当に何をしたいですか?そして、なぜオブジェクトの作成がその親を変えるのでしょうか? – Bergi

+0

@Bergi、私は子供から親のプロパティを変更しています。私はそれら(console.log inside())を変更して見て、それは正常に見えます。しかし、私が外から見ると(console.logの後にvar oo_var = ...)、親はまだ初期値を持っています。 [jsfiddle](https://jsfiddle.net/7rp1qxta/)を参照してください – NestedWeb

答えて

1

コンストラクタは作成のみを行い、何かの状態を変更しないでください。 initメソッドを呼び出す必要はなく、間接的にもchangeメソッドを呼び出す必要はありません。

は、それが子供ではなく、自分自身を変え、親の親を変更するようにしても(if not wrong)ビット奇妙なこと

function OO(o, parent) { 
    this.parent = parent || null; 
    this.type = typeof o; 
    this.obj = this.type === 'object' ? new OO(o.name, this) : o; 
} 
OO.prototype.change = function() { 
    this.parent.obj = 'Orange'; // Holds {} before changing 
    this.parent.type = 'string'; // 'object' before changing 
}; 
OO.prototype.add = function(){ 
    this.parent.another_obj = 'Another'; 
    this.parent.another_type = 'another string'; 
}; 

var oo_var = new OO({name: 'Apple'}); 
console.dir(oo_var); 
oo_var.obj.change(); 
oo_var.obj.add(); 
console.dir(oo_var); 

ください。

あなたがメソッドを自分で呼び出すにしたくない場合は、そのための方法を使用することができます:あなた `init`方法は、後に` `oo_var.obj`と.type`に書き込みを行い

OO.prototype.init = function() { 
    if (this.type === 'object') { 
     this.obj.init(); 
    } else if (this.type === 'string') { 
     this.change(); 
     this.add(); 
    } 
}; 

var oo_var = new OO({name: 'Apple'}); 
console.dir(oo_var); 
oo_var.init(); 
console.dir(oo_var); 
関連する問題