2015-06-20 35 views
1

我在嘗試修改Javascript數組類型的方法,只有當數組中的值不存在時纔會將值推送到數組中。如何修改Javascript中的Array.prototype

這裏是我的代碼:

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

我想這樣做的香草方式。因爲我正在編寫一個開源庫。

+0

嘗試'[] .method('xadd',...' – thefourtheye

+2

'方法'是Array.prototype對象的一個​​方法,''Array'對象和'prototype'的實例有這個方法。 – undefined

+2

它是['Function.prototype.method'](http://stackoverflow.com/q/3966936/1048572)! – Bergi

回答

0

借用劉德華& Nihey我在下面的解決方案修改的陣列式決策「XADD」有條件地提供給陣列

的所有實例到達
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()的變體。

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

+0

好吧,我的意圖是修改數組類型,以便** xadd **可用數組的所有實例我的初始代碼被認爲是實現這一目的的方式,手動將其添加到數組的實例中工作量太大 – timebandit

+0

它*可用於數組的所有實例。 – Andy