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