如何自己手動實現 bind , call 和 apply 函數?

手動實現bind 函數

Function.prototype.my_bind= function (context) { if (typeof this !== 'function') { // this當然必須為 function 對象 throw new TypeError('Error') } let _this = this let args = [...arguments].slice(1) // 保存傳入的參數,供函數執行時傳入 // 返回一個函數 return function F() { // 因為返回了一個函數,我們可以 new F(),所以需要判斷 if (this instanceof F) { return new _this(...args, ...arguments) } return _this.apply(context, args.concat(...arguments)) } }

如何實現一個 call 函數

Function.prototype.my_call = function (context) { var context = context || window // 給 context 添加一個屬性 context.fn = this // 將 context 後面的參數取出來 var args = [...arguments].slice(1) var result = context.fn(...args) // 刪除 fn delete context.fn return result }

如何實現一個 apply 函數

Function.prototype.myApply = function (context) { var context = context || window context.fn = this var result // 需要判斷是否存儲第二個參數 // 如果存在,就將第二個參數展開 if (arguments[1]) { result = context.fn(...arguments[1]) } else { result = context.fn() } delete context.fn return result }