javascript:Array.prototype.slice.call(arguments)

咱們知道,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]

可能剛開始學習js的童鞋並非很能理解這句爲何能實現這樣的功能。好比我就是一個,因此,來探究一下。數組

首先,slice有兩個用法,一個是String.slice,一個是Array.slice,第一個返回的是字符串,第二個返回的是數組,這裏咱們看第2個。dom

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 }
複製代碼
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息