Array.prototype.slice.call(arguments) ---- 学习笔记

  Array.prototype.slice.call(arguments):将具有length属性的对象转成数组。

  代码示例:

var a={length:2,0:'first',1:'second'};
Array.prototype.slice.call(a);//  ["first", "second"]
  
var a={length:2};
Array.prototype.slice.call(a);//  [undefined, undefined]

  虽然有示例,但仍旧不是很能理解为什么这句能实现这样的功能,下面就来探究一下。

  • slice():从已有的数组中返回选定的元素。
    1. String.slice:返回字符串
    2. Array.slice:返回数组

    那么Array.prototype.slice.call(arguments)能够将arguments转成数组,那么就是arguments.toArray().slice(),那么Array.prototype.slice.call(arguments)的过程是不是先将传入进来的第一个参数转为数组,再调用slice?

  • call():call()函数用于调用当前函数functionObject,并可同时使用指定对象thisObj作为本次执行时functionObject函数内部的this指针引用。

    call之后,将当前函数内部this指针引用到对象

那么他的内部实现可能是:

Array.prototype.slice = function(start,end){
     var result = new Array();
     start = start || 0;
     end = end || this.length; 
    //this指向调用的对象,当用了call后,能够改变this的指向,也就是指向传进来的对象,这是关键
     for(var i = start; i < end; i++){
          result.push(this[i]);
     }
     return result;
}

  这个语句第一次看到是在学习柯里化函数时,因为不理解这句代码,所以也有些看不懂柯里化函数,后来理解了这句话,但还是依旧看不懂柯里化函数,但是没关系,知识就时一点儿一点儿累计的。

posted @ 2017-08-14 17:17  Nnn_Lillian  阅读(138)  评论(0编辑  收藏  举报