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的童鞋並非很能理解這句爲何能實現這樣的功能。好比我就是一個,因此,來探究一下。html

首先,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 }
複製代碼

大概就是這樣吧,理解就行,不深究。dom

 

最後,附個轉成數組的通用函數函數

複製代碼
 1 var toArray = function(s){
 2     try{
 3         return Array.prototype.slice.call(s);
 4     } catch(e){
 5             var arr = [];
 6             for(var i = 0,len = s.length; i < len; i++){
 7                 //arr.push(s[i]);
arr[i] = s[i]; //聽說這樣比push快 8 } 9 return arr; 10 } 11 }
複製代碼

 轉:http://www.cnblogs.com/littledu/archive/2012/05/19/2508672.html學習

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息