【问题标题】:extending Javascript object feature set扩展 Javascript 对象功能集
【发布时间】:2017-02-09 13:03:55
【问题描述】:

我不是 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(...); 但不起作用。

【问题讨论】:

    标签: javascript jquery oop


    【解决方案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)
      );    
    
    });
    

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    相关资源
    最近更新 更多