2011-04-17 178 views
1

哪種方法可以從JavaScript中的另一個名稱空間訪問函數或屬性?例如:JavaScript名稱空間


var NS = {}; 
NS.A = { 
    prop1: 'hello', 
    prop2: 'there', 
    func: function() {alert('boo');} 
}; 

NS.B.C = { 

    func1: function() { 
     // Here I want to access the properties and function from the namespace above 
     alert(NS.A.prop1 + NS.A.prop2); // ? 
     NS.A.func(); // ? 
    } 

}; 

NS.B.C.func1(); 
+0

好吧,但是我必須爲每個要訪問的屬性或函數寫入100次NS.A嗎?或者我應該更好地創建一個指向NS.A的局部變量?事實上,我正在嘗試第二種,但也不覺得它很乾淨。 – user287966 2011-04-17 16:54:05

+0

你應該閱讀關於JavaScript關閉。在NS.A之外有一個局部變量指向外部,肯定比在變量外部引用一個變量更快。 – Mickel 2011-04-17 17:03:53

回答

4

當然,一個「命名空間」在JavaScript是其中的相關聯的功能和數據的片段的集合被存儲(而不是有許多全局的,一個用於每個功能和僅全球對象一塊數據)。

您的示例不起作用的唯一原因是當您嘗試爲其分配C屬性時,NS.B未定義。

2

NS.B.C導致錯誤......這樣的事情應該爲你工作:

NS.B = { 
    C: { 
    func1: function() { 
     // Here I want to access the properties and function from the namespace above 
     alert(NS.A.prop1 + NS.A.prop2); // ? 
     NS.A.func(); // ? 
    } 
    } 
}; 

http://jsbin.com/eweta5/2例如。

相關問題