美文网首页
call、apply、bind

call、apply、bind

作者: 糕糕AA | 来源:发表于2019-06-27 14:12 被阅读0次
  • call apply bind

  • call()方法可以指定一个this的值(第一个参数),并且分别传入参数(第一个参数后面的就是需要传入函数的参数,需要一个一个传)

  • 可以将this绑定到call定义的对象中,也可以绑定一个空

  • apply() 传入参数数组(参数需要在一个数组或者类数组中)

  • 如果我们是在一个函数当中使用,那我们还可以直接使用arguments这个类数组对象

       function mySayYourWeapon(num, num2) {
          sayYourWeapon.apply(zoro, arguments) 
        }
  • bind()方法不会立即执行目标函数,而是返回一个原函数的拷贝,并且拥有指定this值和初始函数(为什么是指定的,当然是我们自己传进去的啦)

  • ❗️手写bind方法

      if (!Function.prototype.bind) {
        Function.prototype.bind = function(oThis) {
          if (typeof this !== 'function') {
            throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
          }
          var aArgs = Array.prototype.slice.call(arguments, 1);
          var fToBind = this;
          var fNOP = function() {};
          var fBound  = function() {
              return fToBind.apply(this instanceof fBound ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
          };
          if (this.prototype) {
            fNOP.prototype = this.prototype;
          }
          fBound.prototype = new fNOP();
          return fBound;
        };
      }

相关文章

网友评论

      本文标题:call、apply、bind

      本文链接:https://www.haomeiwen.com/subject/gefrcctx.html