JavaScript常见面试题:new的时候做了什么?

2022-10-24  本文已影响0人  470d98b91bd3

分解 new 运算符

手写一个new

function myNew() {
  const obj = {}

  const args = Array.prototype.slice.call(arguments, 0)

  const ctor = args.shift()

  obj.__proto__ = ctor.prototype

  ctor.apply(obj, args)

  return obj
}

另一个更好理解的版本,善用ES6解构,则不需要做类数组转数组的操作


function myNew(ctor, ...args) {
  const obj = {}

  obj.__proto__ = ctor.prototype

  ctor.apply(obj, args)

  return obj
}

上一篇 下一篇

猜你喜欢

热点阅读