【问题标题】:How to modify Array.prototype in Javascript如何在 Javascript 中修改 Array.prototype
【发布时间】:2015-06-20 18:52:20
【问题描述】:

我正在尝试使用一种方法修改 Javascripts 数组类型,该方法仅在数组不存在时才会将值推送到数组。

这是我的代码:

// add a method conditionally
Array.prototype.method = function (name, func){
    if(!this.prototype[name]){
        this.prototype[name] = func;
        return this;
    }
};

// exclusive push
Array.method('xadd', function(value){
    if(this.indexOf(value) === -1){
        this.push(value)
    };
    return this;
});

但是,当我运行代码时,Firefox 中的暂存器会返回:

/*
Exception: TypeError: Array.method is not a function
@Scratchpad/3:19:1
*/

我想要一种普通的方式来做到这一点。不是库,因为我正在编写一个开源库。

【问题讨论】:

  • 试试[].method('xadd',...
  • methodArray.prototype 对象的一个​​方法。 Array 对象和 prototype 的实例具有该方法。

标签: javascript


【解决方案1】:

当您在 Array.prototype 上放置一个方法时,该方法将在 Array 的实例上可用。

// Add the custom method
Array.prototype.method = function() {
    console.log('XXX');
}

var foo = [];
// prints XXX
foo.method();

【讨论】:

    【解决方案2】:

    首先,我会检查该方法是否已经在数组中。不要覆盖现有的原型方法。此外,您没有将func 添加到原型中,而是将其添加到您将要创建的实例中。

    if (!('method' in Array.prototype)) {
        Array.prototype.method = function (name, func) {
            if (!this[name]) this[name] = func;
        }
    }
    

    然后你需要实际创建你的数组实例:

    var arr = [1,2];
    

    此时您可以使用您创建的方法来添加功能。请注意您的问题中您的检查不正确:

    arr.method('xadd', function (value) {
        if (this.indexOf(value) === -1) {
            this.push(value)
        };
    });
    
    arr.xadd(3); // [1,2,3]
    

    DEMO

    【讨论】:

    • 好了,差不多了。我的意图是修改 Array 类型,以便 xadd 可用于数组的所有实例。我最初的代码被认为是这样做的方法。手动将其添加到数组实例中的工作量太大。
    • 可用于数组的所有实例。
    【解决方案3】:

    借用 Andy & Nihey 我已经得出以下解决方案,它修改了 Array 类型,使 'xadd' 有条件地可用于 Array 的所有实例

    if (!('xpush' in Array.prototype)) {
      Array.prototype.xpush = function(value){
        if(this.indexOf(value) === -1){
          this.push(value);
        };
        return this
      };
    }
    
    var a = [1,2,3];
    console.log(a); // Array [ 1, 2, 3 ]
    a.xadd(5);
    console.log(a); // Array [ 1, 2, 3, 5 ]
    a.xadd(3);
    console.log(a); // Array [ 1, 2, 3, 5 ] '3' already present so not added
    

    一个更好的名字是 xpush(),因为它的行为是 push() 的变体。

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 2012-12-09
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      相关资源
      最近更新 更多