2013-11-27 91 views
1

美好的一天!我有這個代碼:模擬陣列功能

function MyArray() {} 
MyArray.prototype.length = 0; 

(function() { 
    var methods = ['push', 'pop', 'shift', 'unshift', 
    'slice', 'splice', 'join']; 
for (var i = 0; i < methods.length; i++) (function(name) { 
    MyArray.prototype[ name ] = function() { 
    return Array.prototype[ name ].apply(this, arguments); 
    }; 
})(methods[i]); 
})(); 

我需要解釋。我明白「方法」是一組真正的方法,它們只是「輸出」到我們的新班級中。但是,這是什麼:MyArray.prototype.length = 0; ?作者創建新的原型屬性並將其賦值爲零。然後使用這個新的屬性!

var mine = new MyArray(); 
mine.push(1, 2, 3); 
assert(mine.length == 3 ... 
..... 

它是如何工作的? 「長度」沒有在上面的代碼中實例化!

+0

*你是什麼意思*實例化*?你可以實例化對象,但這只是一個原始的... – Kiruse

+0

對不起,我的意思是實現。 「長度」屬性沒有任何實現。只分配一個零。 – user2972298

+0

'length'在方法內部使用。它是數組派生的正確功能所必需的。嘗試刪除聲明,看看會發生什麼。你可能會得到一個錯誤,或者可能是不可預知的行爲。 – Kiruse

回答

0

你真的不能子陣列http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/

因此,如果你創建MYARRAY的一個實例,你不能做的:myArr,該[0] = ...

你可以用裏面的MYARRAY陣列和利用陣列功能:

var MyArray=function() { 
    this.arr=[]; 
    [].push.apply(this.arr,arguments); 
    //following doesn't work in older browsers 
    Object.defineProperty(this,"length",{ 
    get:function(){return this.arr.length;}, 
    enumerable:true, 
    configurable:true 
    }); 
} 
MyArray.prototype.valueOf=function(){return this.arr;}; 
(function() { 
    var methods = ['push', 'pop', 'shift', 'unshift', 
    'slice', 'splice', 'join'],i=methods.length 
    while(--i!==-1){ 
    ;(function(name) { 
     MyArray.prototype[ name ] = function() { 
     console.log(arguments); 
     return Array.prototype[ name ].apply(this.arr, arguments); 
     }; 
    }(methods[i])); 
    } 
}()); 

var mArr1=new MyArray(1,2,3); 
console.log(mArr1.slice(0,1)); 
//you cannot do this: myArr1[0]=22; 
3

它被初始化爲零,所以如果你從不調用它的任何函數,它將返回零(像一個真正的數組),而不是未定義的。還需要從零開始,以便方法正確更新。在你的例子中,長度是3,因爲push方法是這樣做的。

+0

好的。但是「長度」不在導出方法的數組中。 「長度」實現在哪裏? – user2972298

+0

什麼是實現?它在第一行中初始化(MyArray.prototype.length = 0;)。長度是'財產'而不是'方法'。 –