2010-07-03 57 views
1

我有一個對象的結構/層次類似下面的功能:稱爲「超級」 JavaScript對象


var obj = { 

    dimensions : { 

     x : 100, 
     y : 100, 
     w : 300, 
     h : 400, 
     cmp : function() { 

      return this.x + this.y; 

     } 

    }, 

    definition : { 

     base : { 

      rect1 : { 

       // how do I get the value of dimensions.x ?? 
       // or, for that matter, is there a way I could call dimensions.cmp()? 


      }, 

      rect2 : { 
       // things go here 
      } 

     } 

    } 

}; 

我的問題是:是要能夠從內部獲得dimensions.x的價值dimensions.definition.rect1函數?

回答

0

你不能動態地做到這一點,一個函數內的值將指向該對象,該函數被綁定爲一個屬性。

例如,如果調用foo.bar.func();,所述this值內func將指foo.bar對象,也沒有辦法來動態確定是否this屬於foo,沒有明確地檢查foo所有屬性(當然預先知道在哪裏檢查)。

請記住,對象是作爲引用處理的,因此可以從很多地方引用對象。如果你正試圖使多個

var obj = { 
    dimensions : { 
    x : 100, 
    y : 100, 
    //... 
    cmp : function() { 
     return this.x + this.y; 
    } 
    }, 
    definition : { 
    base : { 
     rect1 : { 
     foo: function() { 
     obj.dimensions.cmp(); 
     alert(obj.dimensions.x); 
     } 
     } 
     //... 
    } 
    } 
}; 
+0

非常感謝!我以爲這是因爲某些原因不允許的。我曾嘗試過,但似乎我在做一些愚蠢的事情。再次感謝。 – bibhas 2010-07-03 07:09:29

0

我真的不知道你正在試圖完成的任務,但:

不要拿自己和複雜化,發現使用obj參考你的成員,保持簡單這種類型的對象的實例,你可以嘗試這樣的:

function Structure() { 
    this.dimensions = { 
    x: 100, 
    y: 100, 
    w: 300, 
    h: 400 
    }; 
    function Rect(dimensions) { 
    this.dimensions = dimensions; 
    this.func = function() { 
     alert(dimensions.x); 
    } 
    } 
    this.definition = { 
    base: {} 
    }; 
    this.addRect = function(name) { 
    this.definition.base[name] = new Rect(this.dimensions); 
    }; 
}; 

var obj = new Structure(); 
obj.addRect('rect1'); 
obj.addRect('rect2'); 
obj.definition.base.rect1.func(); 
1

停止使用對象文本,當你想這樣的事情:

var obj = new myConstructor(); 


function myConstructor(){ 
    var dimensions = { 

     x : 100, 
     y : 100, 
     w : 300, 
     h : 400, 
     cmp : function() { 

      return this.x + this.y; 

     } 

    }; 

    this.definition = { 

     base : { 

      rect1 : { 

       // how do I get the value of dimensions.x ?? 
       // or, for that matter, is there a way I could call dimensions.cmp()? 

       //Dimensions is like a private var now - in scope for the object. 

       dimensions.cmp(); //that's how you'd call it. 
      }, 

      rect2 : { 
       // things go here 
      } 

     } 

    } 

} 

嘗試將從構造函數創建的JS對象視爲只是忘記關閉和垃圾收集的函數。所有本地變量都會出現並可以在構造函數中定義的公共方法訪問。外部定義的方法,無論是原型還是剛剛添加。但是無法訪問維度。當你這樣做時,把var看作私人的,這一點。作爲公衆。但是你在函數內定義的公共方法可以訪問var的東西。