1. 程式人生 > 其它 >手寫一個簡易的bind函式

手寫一個簡易的bind函式

 1 // bind方法 在建構函式的原型物件上
 2 // 接受的是逗號隔開的引數形式  引數的個數不確定
 3 Function.prototype.bind1 = function () {
 4   // 將 逗號隔開的引數分割成陣列  arguments 可以獲取所有的引數
 5   const args = Array.prototype.slice.call(arguments);
 6   //   從陣列中刪除傳入的this指向 並返回  剩下的都是傳入的引數 shift 從頭部刪除  返回刪除的元素  把this剔除出去 剩下的都是引數  所以要用shift刪除
 7   const _this = args.shift();
8 // 誰呼叫bind1方法 this指向誰 當前函式的this指向 9 const self = this; 10 // 呼叫bind方法 的時候 返回一個函式 11 return function () { 12 // 函式內部通過apply 修改this指向並返回結果 (主要功能 是apply內部實現的) 13 return self.apply(_this, args); 14 }; 15 }; 16 // 定義一個fn1函式 17 function fn1(a, b, c) { 18 console.log("this", this);
19 console.log(a, b, c); 20 return "this is fn1"; 21 } 22 // fn1通過bind修改this指向 返回一個新函式 23 const fn2 = fn1.bind1({ x: 10 }, 10, 20, 30); 24 // 呼叫 這個新函式 25 const res = fn2(); 26 // 列印新函式的返回值 27 console.log(res);