js中new、apply、call、bind的实现原理及用法

1.new关键字: 执行一个构造函数,返回一个实例对象(new 关键字执行之后总会返回一个对象,要么是实例对象,要么是return语句指定的对象)

function _new(constructor, ...args) {
  if (typeof constructor !== 'function') {
    return new Error('constructor must be a function')
  }
  // 创建一个新的实例对象
  const instance = {}
  // 借用构造函数生成实例对象的属性和方法
  const result = constructor.apply(instance, args)
  // 让该对象的原型指向构造函数的原型
  Object.setPrototypeOf(instance, constructor.prototype)
  // 如果构造函数显示地返回了对象,则返回该对象,否则返回新创建的obj对象
  return result && ['object', 'function'].includes(typeof result) ? result : instance
}

2.apply: 改变函数this指向(执行上下文),并执行函数

Function.prototype._apply = function (context, args) {
  // 如果context不为合法对象,则赋值为window
  if (!context || !['object', 'function'].includes(typeof context)) {
    context = window
  }
  context.fn = this
  const result = context.fn(...args)
  delete context.fn
  return result
}

3.call: 同上,但是参数args接受多个参数而非数组

Function.prototype._call = function (context, ...args) {
  if (!context || !['object', 'function'].includes(typeof context)) {
    context = window
  }
  context.fn = this
  const result = context.fn(...args)
  delete context.fn
  return result
}

4.bind: 改变this指向,不同的是其执行结果是返回一个新函数

Function.prototype._bind = function (context, ...args) {
  const self = this;
  const newFunc = function (...rest) {
    self.apply(this instanceof self ? this : context, args.concat(rest))
  }
  if (this.prototype) {
    newFunc.prototype = Object.create(this.prototype)
  }
  return newFunc
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值