2016-10-07 5 views
0

내가 중첩 된 객체 클래스를 통해 루프에 필요 객체에 속성을 추출하는 모든 객체 참조의 프로퍼티의 변경을 반영합니다. 그러나 객체 내부에서 속성 값을 변경하면 이러한 개체의 변수 지주 루트 개체의 값을 변경하지 않습니다. 객체 내부에서 확인하면 새 값이 올바르게 적용됩니다. 나는 기존의 속성으로 들어간 대신에 새 속성을 추가하는 경우자바 스크립트는

그러나, 나는 새로운 액세스 할 수 있습니다.

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. 

js fiddle

나는 많은 수준은 각 레벨의 형제 자매와 객체를 중첩합니다.

+0

귀하의'init' 방법은 oo_var.obj''에 기록 않고'.type'을 자식 객체의 생성 - 그리고 그것의'.change()'후. – Bergi

+0

정말 원하는게 있니? 그리고 왜 객체의 생성이 부모를 바꿀 것입니까? – Bergi

+0

@Bergi, 나는 부모 속성을 자식에서 변경하고 있습니다. 내가 (console.log inside change()) 그들을 변경 한 후에 보면 괜찮아 보인다. 내가 외부에서 볼 때 (var에 oo_var 후 CONSOLE.LOG = ...), 부모는 여전히 초기 값이 있습니다. [jsfiddle] (https://jsfiddle.net/7rp1qxta/)을 참조하십시오. – NestedWeb

답변

1

생성자는 생성을 수행하고 아무것도의 상태를 변경하지 마십시오. 그것은 init 메소드를 호출 할 필요가 없습니다, 그것은 확실히 change 방법 (심지어 간접적으로)를 호출하지 않아야합니다.

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

그것은 아이가 자체를 변경 부모 대신 부모를 변경하는 것도 조금 이상한 (if not wrong)의합니다.

당신이 방법을 직접 호출하지 않으려면, 당신은 그것을위한 방법을 사용할 수 있습니다 애프터

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