2017-02-09 72 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

感谢您的帮助。 –