2014-10-29 96 views
0

我有數組,我想定製他的一些原型的方法。如果我使用:創建數組與原型的方法實現包裝數組原型

arr.push = function(){ 
    doSomething() 
    Array.prototype.push.call(arguments); 
} 

我爲arr創建自己的財產push。但是我想創建一個新的類似於數組的對象,它將使用上一個示例中的方法push進行原型設計。我試圖做出這樣的事情:

// creating new object which prototype linked to _Array.prototype 
var newArr = new (function _Array(){}); 

// setting up method  
_Array.prototype.push = function(){...} 

// copying all data 
arr.forEach(function(val, index){ 
    newArr[index] = val; 
}); 
newArr.length = arr.length 

//updating original array 
arr = Array.prototype.slice.call(newArr); 

是的,在那之後我會得到類似數組的對象,但Array.prototype.slice回報物體不是我_Array.prototype創建數組原型綁定。

那麼我可以用自定義原型創建數組嗎?

回答

1

您可以創建自己的數組是這樣的:

// create own Array object 
var _Array = function() {}; 

// inherit from Array 
_Array.prototype = Object.create(Array.prototype); 
// reset constructor 
_Array.prototype.constructor = _Array; 
// overwrite push method 
_Array.prototype.push = function(){ 
    doSomething() 
    Array.prototype.push.apply(this, arguments); 
}; 

您可以使用它像這樣:

// create own array 
var newArr = new _Array(); 

// push to array 
newArr.push(1, 2, 3); 

// create copy 
var arr = newArr.slice(); 
+0

執行後arr爲空。當我做arr.push() - 調用Array.prototype.push,而不是_Array.prototype.push。用於創建具有自定義原型的數組,其方法執行某些操作並調用Array.prototype的原始方法 – wmbtrmb 2014-10-29 13:06:37

+0

等待。 newArr沒有屬性'push'。有用。 – wmbtrmb 2014-10-29 13:22:37

+1

我不認爲你可以繼承Array:http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/ – HMR 2014-10-29 14:09:25

1

我不認爲你可以繼承陣:http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/

對於例;使用_Array:

var arr = new _Array(); 
arr[10]=22; 
console.log(arr.length);//=0 

取決於您希望擴展數組的行爲類似於數組的多少。

在這種情況下,在每個數組實例上添加函數可能會更好,並將數組實例保留爲數組實例,而不是創建從數組「繼承」的類型(因爲無法從數組繼承) :

function createSpecialArray(){ 
    var ret = new Array(arguments); 
    //shadow push 
    ret.push = createSpecialArray.push; 
    return ret; 
}; 
createSpecialArray.push=function(){ 
    //do other stuff 
    console.log('doing other stuff'); 
    Array.prototype.push.call(this,arguments); 
} 

var arr = createSpecialArray(1,2,3); 
console.log(arr); 
arr[10]=22; 
console.log(arr.length); 
arr.push(33); 
console.log(arr.length); 
+0

感謝您的參考。最終目的是在我沒有改變的方法的情況下(創建Array.isArray的結果)創建完全複製Array行爲的對象,但現在我看到JS無法做到這一點。 – wmbtrmb 2014-10-29 14:53:28

+0

在這個證據上,我認爲自己的財產是唯一的選擇。 – wmbtrmb 2014-10-29 14:54:44