2013-12-11 24 views
3

我有關於原生javascript調用的問題。Javascript:如何檢測數組調用?

我有一個類:

x = function(arr) { this.arr = arr; return this; } 
x.prototype.toArray = function() { 
     return this.arr; 
}; 
x.prototype.test = function() { alert('but i m object too!'); }; 

當我打電話:

var test = new x(['a','b','c']); 

alert(test[0]); 

alert(test.test()); 

需要得到結果 'a' 和 '但讀音字對象呢!'對話框。

我想使用此功能作爲語法糖像在使用選擇器作爲數組返回DOM元素時在覈心中使用jquery。如何實現?

UPDATE:

感謝的答案,但我需要在jQuery代碼BLOB 證明在github

+0

你想對你的對象是*像*一個數組或「繼承」數組所有的方法? –

+1

@Jack我的猜測是*像一個數組。就像你如何使用'$('selector')[0]'從一個jQuery對象獲得DOM元素' – Phil

+0

@Phil是對的。 – xercool

回答

1

基本上jQuery的原型僅具有length特性,這使得它陣列狀;要將項目「導入」它們,它們必須逐一複製。

要執行此合併,他們使用的following function

function merge(first, second) 
{ 
    var len = +second.length, 
    j = 0, 
    i = first.length; 

    for (; j < len; j++) { 
    first[ i++ ] = second[ j ]; 
    } 

    first.length = i; 

    return first; 
} 

接着,它們定義了constructor其也可以作爲函數調用:

function x(arr) 
{ 
    return new x.fn.init(arr); 
} 

x.fnprototype從其功能被繼承,如下所示:

x.fn = x.prototype = { 
    constructor: x, 
    test: function() { 
    alert('yay'); 
    }, 
    init: function(arr) { 
    return merge(this, arr); 
    }, 
    length: 0 
}; 

正如你所看到的,你的test()方法也在那裏,以及初始化的length屬性。剩下的唯一的事情就是bindx.fn.init原型上述x.fn

x.fn.init.prototype = x.fn; 

與所有的地方,下面的代碼按預期工作:

var y = x(['a', 'b', 'c']); 

alert(y[0]); // shows 'a' 
y.test(); // alerts 'yay' 
+0

感謝您的完整解答! – xercool

+0

@xercool不客氣:) –

3

數組只是一種以特殊方式處理數字屬性的對象。您必須將數組的每個元素複製到實例,並使用元素的索引作爲屬性名稱。您還應該設置length屬性,使其成爲真正的「類似數組」的對象。

var X = function(arr) { 
    for (var i = 0, l = arr.length; i < l; i++) { 
     this[i] = arr[i]; 
    } 
    this.length = arr.length; 
}; 

var x = new X(['a', 'b', 'c']); 
alert(x[0]); 
+0

和jQuery使用這種方式? – xercool

+0

最有可能的是。 –

+1

我需要在jquery代碼blob中看到證據。 – xercool

0

爲什麼不調用toArray()創建的?

嘗試:

x = function(arr) { this.arr = arr; } 
x.prototype.toArray = function() { 
     return this.arr; 
}; 

var test = new x(['a','b','c']); 

alert(test.toArray()[0]); 

OR

x = function(arr) { this.arr = arr; } 
x.prototype.toArray = function() { 
     return this.arr; 
}; 

var test = new x(['a','b','c']).toArray(); 

alert(test[0]); 
+0

這仍然不是OP想要的。 –