如何手寫call, apply, bind~

call

Function.prototype.call(this, arg1, arg2, …..) 能夠改變this,而且傳入參數,馬上執行,返回函數返回值javascript

手寫calljava

Function.prototype.myCall = function(context = window, ...args) {
  context = context || window; // 參數默認值並不會排除null,因此從新賦值
  context.fn = this; // this是調用call的函數
  const result = context.fn(...args);
  delete context.fn; // 執行後刪除新增屬性
  return result;
}
複製代碼

apply

Function.prototype.apply(this, [arg1, arg2, …..]) 能夠改變this,而且傳入參數,與call不一樣的是,傳入的參數是數組或類數組,馬上執行,返回函數返回值數組

手寫apply:app

Function.prototype.myApply = function(context = window, args = []) {
  context = context || window; // 參數默認值並不會排除null,因此從新賦值
  context.fn = this; // this是調用call的函數
  const result = context.fn(...args);
  delete context.fn;
  return result;
}
複製代碼

bind

Function.prototype.bind(this, arg1, arg2, …) 能夠綁定this,而且傳入參數,方式與call相同,可是不會執行,返回已綁定this的新函數函數

手寫bind:ui

Function.prototype.myBind = function(context, ...args) {
  const _this = this;
  return function Bind(...newArgs) {
    // 考慮是否此函數被繼承
    if (this instanceof Bind) {
      return _this.myApply(this, [...args, ...newArgs])
    }
    return _this.myApply(context, [...args, ...newArgs])
  }
}
複製代碼
相關文章
相關標籤/搜索