美文网首页
call、bind、apply

call、bind、apply

作者: 青城墨阕 | 来源:发表于2022-06-21 19:03 被阅读0次

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

不同点:
  • 三者第一个参数都是this要指向的对象,如果如果没有这个参数或参数为undefined或null,则默认指向全局window
  • 三者都可以传参,但是apply是数组,而call是参数列表,且apply和call是一次性传入参数,而bind可以分为多次传入
  • bind 是返回绑定this之后的函数,apply 、call 则是立即执行
手动实现一个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));
  }
}

相关文章

网友评论

      本文标题:call、bind、apply

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