call、bind、apply

2022-06-21  本文已影响0人  青城墨阕

相同点:三者都可以改变函数的this对象指向

不同点:
手动实现一个call
Function.prototype.myCall = function(context, ...args) {
  // 首先判断调用对象
  if(typeof this !== 'function') {
    console.log('type error')
  }
  result = null
  // 判断content(this指针要指向的对象)是否传入, 如果没有设置为window
  context = context || window
  // 将调用函数设置为对象的方法
  context.fn = this
  // 调用函数
  result = context.fn(...args);
  // 删除属性
  delete context.fn
  return result
}
实现效果对比

手动实现一个apply
Function.prototype.myApply = function (context, args = []) {
  // 首先判断调用对象是否为函数
  if(typeof this !== 'function') {
    throw new TypeError('error')
  }
  let result = null
 // 判断content(this指针要指向的对象)是否传入, 如果没有设置为window
  context = context || window
  // 把当前调用的函数赋值给传入对象的
  context.fn = this
  // 调用赋值的函数
  result = context.fn(...args);
  delete context.fn;
  return result;
}
实现效果对比

手动实现一个bind
Function.prototype.myBind = function(context, ...args1) {
  if (typeof this !== 'function') {
    throw new TypeError('error')
  }
  let _this = this // 调用对象
  return function Fn(...args2) {
    if (this instanceof Fn) {
        return new _this(...args1, ...args2);
    }
    return _this.apply(context, args1.concat(...args2));
  }
}
上一篇 下一篇

猜你喜欢

热点阅读