模擬call、apply和bind方法以及new操作符的實現(xiàn)

在模擬實現(xiàn) call、apply 和 bind 方法以及 new 操作符的過程中,能讓我們更好的理解他們的運行原理。

1、區(qū)別

call 、apply 和 bind 方法都是為了解決改變 this 的指向。

call 、apply 方法都是在傳入一個指定的 this 值和若干個指定的參數(shù)值的前提下調(diào)用某個函數(shù)或方法。作用都是相同的,只是傳參的形式不同。
除了第一個參數(shù)外,call 接收一個參數(shù)列表,apply 接受一個參數(shù)數(shù)組。使用 call 、apply 方法該函數(shù)會被執(zhí)行

bind 和其他兩個方法作用也是一致的,只是該方法會返回一個函數(shù)。即使用 bind 方法該函數(shù)不會被執(zhí)行(返回該函數(shù))。并且我們可以通過 bind 實現(xiàn)柯里化。

let a = {
    value: 1
}
function getValue(name, age) {
    console.log(name, age)
    console.log(this.value)
}
getValue.call(a, 'xql', '18')
getValue.apply(a, ['xql', '18'])

getValue.bind(a, 'xql', '18') 
// getValue.bind(a, 'xql', '18')() 執(zhí)行該函數(shù)

2、模擬實現(xiàn) call 和 apply

  1. 先看看call 和 apply 方法發(fā)生了什么?
  • 改變了 this 的指向,指向到 a
  • getValue 函數(shù)執(zhí)行了
  1. 該怎么模擬實現(xiàn)這兩個效果呢?

既然 call 和 apply 方法是改變了 this 指向,讓新的對象可以執(zhí)行該函數(shù),那么思路是否可以變成給新的對象添加一個函數(shù)(將函數(shù)設為對象的屬性),然后在執(zhí)行完以后刪除?

Function.prototype.myCall = function(objCtx) {
    if (typeof this !== 'function') {
      throw new TypeError('Error')
    }

    let ctx = objCtx || window;
    let args = [...arguments].slice(1);
    // let args = Array.prototype.slice.call(arguments, 1)
    
    ctx.fn = this;
    let result = ctx.fn(...args);
    delete ctx.fn;
    return result; // 函數(shù)是可以有返回值的
}

// 測試一下
let a = {
    value: 1
}

function getValue(name, age) {
    console.log(this.value)
    return {
        name: name,
        age: age,
        value: this.value
    }
}

getValue.myCall(a, 'xql', '19')
getValue.myCall(null)
console.log(a)

fn 是對象的屬性名,因為最后要delete,這里可以是任意名稱。

以上就是 call 方法的思路,apply 方法的實現(xiàn)也類似。

Function.prototype.myApply = function(objCtx) {
    if (typeof this !== 'function') {
      throw new TypeError('Error')
    }

    let ctx = objCtx || window;
    ctx.fn = this; // 屬性名fn可以任意
    
    let result;
    // 需要判斷是否存在第二個參數(shù)
    if (arguments[1]) {
        result = ctx.fn(...arguments[1]);
    } else {
        result = ctx.fn();
    }
    delete ctx.fn;
    return result;
}

3、bind 方法的模擬實現(xiàn)

  1. bind 函數(shù)的兩個特點?
  • 可以傳入?yún)?shù)
  • 返回一個函數(shù)

① 其中,對于 bind 函數(shù)中的傳入?yún)?shù)有個特點

既然在使用 bind 函數(shù)的時候,是可以傳參的。那么,在執(zhí)行 bind 返回的函數(shù)的時候,可不可以傳參呢? 類似函數(shù)柯里化。

let foo = {
    value: 1
};

function getValue(name, age) {
    console.log(this.value);
    console.log(name, age);
}

let bindFoo = getValue.bind(foo, 'xql');
bindFoo('18');

② 另外,因為 bind 函數(shù)返回一個新函數(shù),所以 bind 函數(shù)還有一個特點

當 bind 返回的函數(shù)作為構(gòu)造函數(shù)的時候,bind 時指定的 this 值會失效,但傳入的參數(shù)依然生效。

一個綁定函數(shù)也能使用new操作符創(chuàng)建對象:這種行為就像把原函數(shù)(調(diào)用 bind 方法的函數(shù))當成構(gòu)造器。提供的 this 值被忽略,同時調(diào)用時的參數(shù)被提供給模擬函數(shù)。

  var value = 2;
  
  var foo = {
      value: 1
  };

  function bar(name, age) {
      this.habit = 'shopping';
      console.log(this.value);
      console.log(name, age);
  }

  bar.prototype.friend = 'shuaige';

  let bindFoo = bar.bind(foo, 'xql');
  var obj = new bindFoo('18');
  // undefined 這里對 bind 函數(shù)綁定的 this 失效了
  // xql 18
  console.log(obj.habit);
  console.log(obj.friend);

注意:盡管在全局和 foo 中都聲明了 value 值,最后依然返回了 undefind,說明綁定的 this 失效了,這里可以查看 new 的模擬實現(xiàn),就會知道這個時候的 this 已經(jīng)指向了 obj。

  1. 實現(xiàn)步驟
  • 首先實現(xiàn)傳參;
Function.prototype.myBind = function (objCtx) {
    let ctx = objCtx || window;
    let _this = this;
    let args = [...arguments].slice(1);
    
    return function () {
        // 這里的 arguments 與上面的 arguments 的值是不同的 這里是對返回函數(shù)所傳入的參數(shù)  下面是將類數(shù)組 arguments 轉(zhuǎn)為數(shù)組的兩種方式 這里在使用的時候要記得轉(zhuǎn)化為數(shù)組 
        // args.concat(arguments) 這樣使用會出現(xiàn)問題 arguments 是個類數(shù)組對象
        // let bindArgs = [...arguments]
        // let bindArgs = Array.prototype.slice.call(arguments)
        return _this.apply(ctx, args.concat(...arguments)) // 為什么要寫return 因為綁定函數(shù)(函數(shù))是可以有返回值的
    }
}

// 測試一下
  var foo = {
      value: 1
  };
  
  function bar(name, age) {
      this.habit = 'shopping';
      console.log(this.value);
      console.log(name, age);
  }
  
  let bindFoo = bar.myBind(foo, 'xql');
  bindFoo('1111')

  • 其次,實現(xiàn)綁定函數(shù)(調(diào)用 bind 方法的函數(shù))作為構(gòu)造函數(shù)進行使用的情況;
Function.prototype.myBind = function (objCtx) {
    let ctx = objCtx || window;
    let _this = this;
    let args = [...arguments].slice(1);
    
    let Fbind = function () {
        // 當 Fbind 作為構(gòu)造函數(shù)時,這里的 this 指向?qū)嵗?        let self = this instanceof Fbind ? this : ctx;
        return _this.apply(self, args.concat(...arguments));
    }
    
    Fbind.prototype = this.prototype; // // 修改返回函數(shù)的 prototype 為綁定函數(shù)的 prototype,實例就可以繼承綁定函數(shù)的原型中的值
    // 不要寫成 Fbind.prototype = ctx.prototype;
    
    return Fbind;
}

這里,我們直接將 Fbind.prototype = this.prototype,會導致修改 Fbind.prototype 的時候,也會直接修改綁定函數(shù)的 prototype。這個時候,我們可以通過一個空函數(shù)來進行中轉(zhuǎn)( js 高程中成為原型式繼承)。

  1. 最終的實現(xiàn)為:
Function.prototype.myBind = function (objCtx) {
    if (typeof this !== 'function') {
        throw new TypeError('Error');
    }
    let ctx = objCtx || window;
    let _this = this;
    let args = [...arguments].slice(1);
    
    let Fbind = function () {
        let self = this instanceof Fbind ? this : ctx;
        return _this.apply(self, args.concat(...arguments));
        // 這里可以使用 call 方法
        // let bindArgs = args.concat(...arguments);
        // return _this.call(self, ...bindArgs);
    }
    
    let f = function () {};
    f.prototype = this.prototype;
    Fbind.prototype = new f();
    
    return Fbind;
}

 // 測試一下 
 var value = 2;

 var foo = {
     value: 1
 };

 function bar(name, age) {
     this.habit = 'shopping';
     console.log(this.value); // undefined
     console.log(name, age);
 }

 bar.prototype.friend = 'shuaige';

 var bindFoo = bar.myBind(foo, 'xql');
 var obj = new bindFoo('18');
 console.log(obj.habit);
 console.log(obj.friend);

其中,Object.create()模擬實現(xiàn)為:(Object.create()方法創(chuàng)建一個新對象,使用現(xiàn)有的對象來提供新創(chuàng)建的對象的__proto__。 )

Object.create = function( o ) {
    function f(){}
    f.prototype = o;
    return new f;
};

4、new操作符的模擬實現(xiàn)

通過 new 操作符的模擬實現(xiàn),來看看使用 new 獲得構(gòu)造函數(shù)實例的原理。

  1. 先來看看使用 new 操作符發(fā)生了什么?
  • 創(chuàng)建一個空對象;
  • 該空對象的原型指向構(gòu)造函數(shù)(鏈接原型):將構(gòu)造函數(shù)的 prototype 賦值給對象的 __proto__屬性;
  • 綁定 this:將對象作為構(gòu)造函數(shù)的 this 傳進去,并執(zhí)行該構(gòu)造函數(shù);
  • 返回新對象:如果構(gòu)造函數(shù)返回的是一個對象,則返回該對象;否則(若沒有返回值或者返回基本類型),返回第一步中新創(chuàng)建的對象;

舉例說明:

  • 構(gòu)造函數(shù)沒有返回值的情況:
  function Angel (name, age) {
      this.name = name;
      this.age = age;
      this.habit = 'Games';
  }

  Angel.prototype.strength = 60;

  Angel.prototype.sayYourName = function () {
      console.log('I am ' + this.name);
  }

  var person = new Angel('xql', '18');
  console.log(person.name, person.habit, person.strength) // xql Games 60
  person.sayYourName(); // I am xql
  • 構(gòu)造函數(shù)有返回值的情況:返回對象 or 返回基本類型(返回 null )
  function Angel (name, age) {
      this.strength = 60;
      this.age = age;

      return {
          name: name,
          habit: 'Games'
      }
  }

  var person = new Angel('xql', '18');
  console.log(person.name, person.habit) // xql Games 60
  console.log(person.strength, person.age) // undefined undefined
  function Angel (name, age) {
      this.strength = 60;
      this.age = age;

      return '111' // 和沒有返回值以及 return null 效果是一樣的
  }

  var person = new Angel('xql', '18');
  console.log(person.name, person.habit) // undefined undefined
  console.log(person.strength, person.age) // 60 "18"
  1. 具體實現(xiàn)

因為 new 是關(guān)鍵字, 我們只能寫一個函數(shù)來模擬了,構(gòu)造函數(shù)作為參數(shù)傳入。

// 使用 new
var person = new Angel(……);
// 使用 objectFactory
var person = objFactory(Angel, ……)
function objFactory () {
  let obj = {};
  // let obj = new Object ();
  // 取出參數(shù)中的第一個參數(shù)即構(gòu)造函數(shù), 并將該參數(shù)從 arguments 中刪掉
  let Con = [].shift.call(arguments); // 不要寫成 [].prototype.shift.call(arguments)
  
  obj._proto_ = Con.prototype;
  
  let result = Con.apply(obj, arguments);
  // let result = Con.apply(obj, [...arguments]);
  // let result = Con.call(obj, ...arguments)
  
  return Object.prototype.toString.call(result) === '[object Object]' ? result : obj;
  // 這里用typeof result == 'object' 進行判斷會有個問題:當構(gòu)造函數(shù)返回 null 時,會報錯,因為 typeof null == 'object'
  // 應該是除了構(gòu)造函數(shù)返回一個對象,其他的都返回新創(chuàng)建的對象
}

 // 測試一下
function Angel (name, age) {
  this.strength = 60;
  this.age = age;
  return null
}

var person = objFactory(Angel, 'Kevin', '18');
console.log(person.name, person.habit); // undefined undefined
console.log(person.strength, person.age) // 60 "18"

3、 小知識點

  1. 對于創(chuàng)建一個對象來說,更推薦使用字面量的方式創(chuàng)建對象(無論性能上還是可讀性)。因為你使用 new Object() 的方式創(chuàng)建對象需要通過作用域鏈一層層找到 Object,但是你使用字面量的方式就沒這個問題。
  2. 對于 new 來說,還需要注意下運算符優(yōu)先級。
function Foo() {
    return this;
}
Foo.getName = function () {
    console.log('1');
};
Foo.prototype.getName = function () {
    console.log('2');
};

new Foo.getName();   // -> 1
new Foo().getName(); // -> 2   

References

JavaScript深入系列
new

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容