call、apply、bind的实现

52 阅读1分钟

call、apply、bind的使用

    function sayHello(to) {
      console.log(`${this.name} say hello to ${to}`);
    };

    const jack = {
      name: 'jack'
    };

    sayHello.call(jack,'tom');  // jack say hello to tom
    sayHello.apply(jack,['tom']); // jack say hello to tom
    sayHello.bind(jack)('tom'); // jack say hello to tom

Function.prototype.myCall的实现

核心思路是给context添加一个属性,将原函数指向这个属性,再通过context调用原函数

    Function.prototype.myCall = function (context, ...args) {
      if (typeof context === undefined || context === null) {
        context = window;
      };
      const symbol = Symbol();
      context[symbol] = this;
      const result = context[symbol](...args);
      delete context[symbol];
      return result;
    };

Function.prototype.myApply的实现

与 Function.prototype.myCall类似,只有入参形式有所区别

    Function.prototype.myApply = function (context,args) {
      if (typeof context == "undefined" || context === null) {
        context = window;
      };
      const symbol = Symbol();
      context[symbol] = this;
      const result = context[symbol](...args);
      
      return result;
    };

Function.prototype.myBind的实现

    Function.prototype.myBind = function(context,...args){
      if(typeof context ==='undefined' || context===null){
         context = window;
      };
      const symbol = Symbol();
      context[symbol] = this;
      return function(..._args){
        context[symbol](...args,..._args);
      }
    };