2013-03-19 26 views
1

我有以下對象。如何獲得父/包裝對象的引用?

ou.map : { 
    settings : { 
    }, 

    basePath : './path/'; 
    marker_setting : { 
    img : this.basePath + 'image.png'; 
    }, 

    fun : function() { 
     alert (this.maker_setting.img ); 
     //alert (this.basePath + this.maker_setting.img); Right now, I am using this where this.maker_setting.img is simply 'image.png' 
    } 

} 

這裏,ou.map.marker_setting.img價值出來是undefinedimage.png,但我想這是./path/image.png。我怎樣才能做到這一點?

編輯
我願意改變完整的方法。我想要的是,一個命名空間具有marker_setting和basePath,以及一個可以在marker_setting中使用屬性的主要方法。

另外,我嘗試了所有這些

img : this.basePath + 'image.png'; 
img : basePath + 'image.png'; 
img : ou.map.basePath + 'image.png'; 

無,這些給了所需的輸出。讓我知道是否需要其他信息。

+4

這裏'this'指的是其中的語句被執行的上下文。 – Diode 2013-03-19 07:32:41

+0

看看[Javascript對象:得到父](http://stackoverflow.com/questions/2980763/javascript-objects-get-parent) – 2013-03-19 07:48:45

+0

這個答案使用初始化函數來初始化一個父http:// stackoverflow。 com/a/10170826/2022859 – 2013-03-19 07:58:13

回答

0

this的值取決於上面代碼的執行方式和位置,即在您的情況下定義了對象的上下文。

例如:

function foo() { 
    ou.map = { 
     // here this would be 'x' 
    } 
} 

foo.call('x'); // means the value of "this" inside foo() will be 'x' 
+0

這是行不通的,在這種情況下你會如何引用自我? – Elad 2013-03-19 07:44:12

+0

編輯了刪除「self」部分的答案。其他信息可能對其他人有用。 – techfoobar 2013-03-19 08:02:01