【发布时间】:2011-03-04 15:27:56
【问题描述】:
var Test = (function() {
return {
useSub: function () {
this.Sub.sayHi();
},
init: function () {
$(document).ready(this.useSub);
}
};
})();
Test.Sub = (function () {
return {
sayHi: function () {
alert('hi');
}
};
})();
Test.useSub(); // works
Test.init(); // explodes
上面我正在尝试创建一个 Test 命名空间并向其中添加一个对象 Sub。在我尝试在 jQuery 中使用该对象之前,我做得很好。错误是“未捕获的 TypeError:无法调用未定义的方法 'sayHi'”。如果有更好的方法可以做到这一点,我愿意接受。
编辑:
显然这是演示代码。在我的实际应用中,我使用的解决方案是因为我认为最清楚的是这个:
var Namespace (function () {
return {
init: function () {
$(document).ready(function() {
Namespace.onReady();
}
},
onReady: function() {
alert('Now I am back in the Namespace scope. Proceed as planned');
}
};
})();
Edit2:所有 jQuery 回调似乎都要求以这种方式使用它们,否则范围就会搞砸。
【问题讨论】:
标签: javascript jquery namespaces