a.call(b) 至关于把a方法放到b的原型上(实例私有方法)执行html
Array.slice的用途
https://juejin.im/post/5b20b8596fb9a01e8d6a47c0 用法一: slice方法用于提取目标数组的一部分,返回一个新数组,原数组不变。数组
//取数组切片 arr.slice(start, end); var arr = [0,1,2]; var arr2 = arr.slice(); // 至关于复制一份,[0,1,2] var arr3 = arr.slice(0); // 至关于复制一份,[0,1,2]
用法二: slice方法的一个重要应用,是将相似数组的对象转为真正的数组。post
Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 }) // ['a', 'b'] Array.prototype.slice.call(document.querySelectorAll("div")); Array.prototype.slice.call(arguments);
var a = function(){ console.log(this); // 'littledu' console.log(typeof this); // object, 是String类的一个实例 console.log(this instanceof String); // true }; a.call('littledu'); console.log(typeof new String('littledu'));
Array.prototype.slice.call原理
https://www.cnblogs.com/littledu/archive/2012/05/19/2508672.htmlthis
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放到a环境里执行
Array.slice实现原理
咱们能够大胆猜一下slice的内部实现spa
Array.prototype.myslice = 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; }; var arr = [0, 1, 2, 3]; console.log(arr.myslice(1, 3)); console.log(arr.slice(1, 3));
另参考: http://www.javashuo.com/article/p-vgnrgskn-cr.htmlprototype