Blog icon indicating copy to clipboard operation
Blog copied to clipboard

原型与原型链 - new的详细过程及其模拟实现

Open logan70 opened this issue 5 years ago • 0 comments

new的详细过程及其模拟实现

new一个对象的详细过程

  1. 创建一个全新对象,并将该对象原型指向构造函数的原型对象;
  2. 将构造函数调用的this指向这个新对象,并执行构造函数;
  3. 如果构造函数执行结果为对象类型(包含Object,Functoin, Array, Date, RegExg, Error等),则返回执行结果,否则返回创建的新对象。

模拟实现new

function newOperator(Ctor, ...args) {
  if (typeof Ctor !== 'function') {
    throw new TypeError('First argument is not a constructor')
  }
  // 1. 创建一个全新对象,并将该对象原型指向构造函数的原型对象
  const obj = Object.create(Ctor.prototype)

  // 2. 将构造函数调用的this指向这个新对象,并执行构造函数;
  const result = Ctor.apply(obj, args)

  // 3. 如果构造函数执行结果为对象类型,则返回执行结果,否则返回创建的新对象
  return (result instanceof Object) ? result : obj
}

logan70 avatar Nov 22 '19 01:11 logan70