关于call --- bind --- apply 的区别

解决this指向问题:
1.call-bind作用是相同的,只是传参方式不同,call接收的参数列表,apply接收一个参数数组。
2.bind绑定返回一个函数,是不执行的。

   Function.prototype.myCall = function (context = window) {
   context.fn = this;

  var args = [...arguments].slice(1);

  var result = context.fn(...args);
  // 执行完后干掉
  delete context.fn;
  return result;
}
Function.prototype.myApply = function (context = window) {
  context.fn = this;

  var result
  // 判断 arguments[1] 是不是 undefined
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }

  delete context.fn
  return result;
Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  var _this = this
  var args = [...arguments].slice(1)
  // 返回一个函数
  return function F() {
    // 因为返回了一个函数,我们可以 new F(),所以需要判断
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
}

拿取之地

猜你喜欢

转载自www.cnblogs.com/keenjade/p/11243829.html