我在嘗試修改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
*/
我想這樣做的香草方式。因爲我正在編寫一個開源庫。
嘗試'[] .method('xadd',...' – thefourtheye
'方法'是Array.prototype對象的一個方法,''Array'對象和'prototype'的實例有這個方法。 – undefined
它是['Function.prototype.method'](http://stackoverflow.com/q/3966936/1048572)! – Bergi