2017-02-09 63 views
0

我不是一個JavaScript專家,並試圖弄清楚如何擴展現有對象。擴展Javascript對象功能集

HTML:

<li data-brandtarget="Netherlands"><img src="images/netherlands.png" alt="Netherlands">Netherlands</li> 
<li data-brandtarget="Netherlands"><img src="images/netherlands.png" alt="Netherlands">Netherlands</li> 

JS:

MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
    // Brand Fetures 
    new storeLocator.Feature('Aquafleur-YES', 'Aquafleur'), 
    new storeLocator.Feature('Aquafarm-YES', 'Aquafarm'), 
    new storeLocator.Feature('Bm_Web-YES', 'Blue Marine'), 
    // The below mentioned features I want to be added based on a loop 
    //new storeLocator.Feature('Naamlandnat-Netherlands', 'Netherlands'), 
    //new storeLocator.Feature('Naamlandnat-Great Britain', 'Great Britain'), 
    //new storeLocator.Feature('Naamlandnat-France', 'France'), 
    //new storeLocator.Feature('Naamlandnat-Germany', 'Germany') 
); 

我試圖使國傢俱有動態。所以我正在遍歷所有列表並獲取屬性。現在循環如何擴展和添加新功能到現有的對象?以下是我的方法

jQuery('.country-options li').each(function(){ 

    var countryName = jQuery(this).attr('data-brandtarget'); 

    MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
     // Country Features 
     new storeLocator.Feature('Naamlandnat-'+ countryName, countryName) 
    );  

}); 

我知道這是錯誤的,因爲我想:我與每一個覆蓋現有對象,因此只有最後一個功能在對象保持循環一次又一次地創建新的對象。

那麼,什麼是擴展功能,而無需重寫現有的功能在這裏設置的正確方法?

我也嘗試:通過刪除new,並保持它只是storeLocator.FeatureSet(...);內循環,但沒有奏效

回答

1

按照reference我發現,您可以在現有FeatureSet撥打add()

MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(); 

jQuery('.country-options li').each(function(){ 

    var countryName = jQuery(this).attr('data-brandtarget'); 

    MedicareDataSource.prototype.FEATURES_.add(
    new storeLocator.Feature('Naamlandnat-'+ countryName, countryName) 
);  

}); 
+0

感謝您的幫助。 –