KFCVme50-CrazyThursday / sheng-study

个人学习总结与代码知识点
1 stars 0 forks source link

5、bind #5

Open KFCVme50-CrazyThursday opened 4 years ago

KFCVme50-CrazyThursday commented 4 years ago

mdn 是这么描述的:

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,
而其余参数将作为新函数的参数,供调用时使用。

mdn 的实现:

// Does not work with `new funcA.bind(thisArg, args)`
if (!Function.prototype.bind) (function(){
  var slice = Array.prototype.slice;
  Function.prototype.bind = function() {
    var thatFunc = this, thatArg = arguments[0];
    var args = slice.call(arguments, 1);
    if (typeof thatFunc !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - ' +
             'what is trying to be bound is not callable');
    }
    return function(){
      var funcArgs = args.concat(slice.call(arguments))
      return thatFunc.apply(thatArg, funcArgs);
    };
  };
})();