Array.prototype.slice.call(arguments)能將具有length屬性的對象轉成數組,除了IE下的節點集合(因為ie下的dom對象是以com對象的形式實現的,js對象與com對象不能進行轉換)
如:
1 var a={length:2,0:'first',1:'second'}; 2 Array.prototype.slice.call(a);// ["first", "second"] 3 4 var a={length:2}; 5 Array.prototype.slice.call(a);// [undefined, undefined]
首先,slice有兩個用法,一個是String.slice,一個是Array.slice,第一個返回的是字符串,第二個返回的是數組,這里我們看第2個。
Array.prototype.slice.call(arguments)能夠將arguments轉成數組,那么就是arguments.toArray().slice();到這里,是不是就可以說Array.prototype.slice.call(arguments)的過程就是先將傳入進來的第一個參數轉為數組,再調用slice?
?
再看call的用法,如下例子
1 var a = function(){ 2 console.log(this); // 'littledu' 3 console.log(typeof this); // Object 4 console.log(this instanceof String); // true 5 } 6 a.call('littledu');
可以看出,call了后,就把當前函數推入所傳參數的作用域中去了,不知道這樣說對不對,但反正this就指向了所傳進去的對象就肯定的了。
到這里,基本就差不多了,我們可以大膽猜一下slice的內部實現,如下
1 Array.prototype.slice = function(start,end){ 2 var result = new Array(); 3 start = start || 0; 4 end = end || this.length; //this指向調用的對象,當用了call后,能夠改變this的指向,也就是指向傳進來的對象,這是關鍵 5 for(var i = start; i < end; i++){ 6 result.push(this[i]); 7 } 8 return result; 9 }
大概就是這樣吧,理解就行,不深究。