在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();发布于 2011-04-18 00:48:27
当然,JavaScript中的“名称空间”只是一个全局对象,其中存储了相关函数和数据片段的集合(而不是有许多全局变量,每个函数和数据片段对应一个全局变量)。
示例不起作用的唯一原因是,当您尝试为其分配C属性时,NS.B是未定义的。
发布于 2011-04-18 00:49:46
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示例。
https://stackoverflow.com/questions/5694861
复制相似问题