簡體   English   中英

如何在Javascript中修改Array.prototype

[英]How to modify Array.prototype in Javascript

我正在嘗試使用一種方法修改Javascripts Array類型,該方法僅在值不存在時才將其推入數組。

這是我的代碼:

// 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
*/

我想要一種香草的方式。 不像我在寫一個開源庫那樣的庫。

首先,我將檢查該方法是否已在數組中。 不要覆蓋現有的原型方法。 此外,您沒有將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.prototype該方法將在Array實例上可用。

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

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

從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()的變體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM