[英]What is the difference between a JS object using literal notation and a namespace
[英]Extend object in namespace using literal notation
我有一個頁面,其中包含許多元素,例如輸入和選擇框,這些元素需要分別添加控制其特定行為的功能。
我的代碼當前為:
var mpp_ui = {
itemList : document.getElementById('mpp_itemlist')
};
mpp_ui.itemList.clear = function(){
while(this.length > 0){
this.remove(0);
}
};
其中mpp_ui
用作命名空間,其中包含需要mpp_ui.itemList
分配功能的所有元素,而mpp_ui.itemList
是HTML select元素。
如果有可能,我希望避免在每個函數語句中都鍵入mpp_ui。 我想聲明這樣的功能(部分偽代碼,因為我不太了解如何處理):
var mpp_ui = {
itemList : {
DEFINE IT AS document.getElementById('mpp_itemlist').
Then extend it with functions like so:
clear : function(){
while(this.length > 0){
this.remove(0);
}
}
}
}
或者,如果以上操作不可行:
var mpp_ui = {
itemList : document.getElementById('mpp_itemlist'),
itemList.clear : function(){
while(this.length > 0){
this.remove(0);
}
}
}
最后的代碼是我嘗試的第一件事,但是它給了我SyntaxError: Unexpected token .
在定義itemList.clear
的行上。
在挖掘了很多選項之后,最接近所需格式的方法是在名稱空間中聲明元素,然后使用所需函數擴展它們,為此我使用了underscore.js 。 結果:
mpp_ui = {
itemList : document.getElementById('mpp_itemlist')
};
_(mpp_ui.itemList).extend({
clear : function(){
while(this.length > 0){
this.remove(0);
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.