Skip to the content.

new 运算符新建一个对象的过程

  1. 创建了一个对象,此对象绑定到构造函数的this
  2. 将此对象的__proto__设置为构造函数的prototype
  3. 通过执行构造函数,对对象进行初始化操作
  4. 返回this指向的新对象

若自己实现一个new功能,则必须要满足上面的条件


/**
 * @param constructorFn 构造函数
 * @param ...args 构造函数的参数
 * */
function newMethod(constructorFn, ...args) {
  // 1. 创建一个空对象,构造函数的this将是此对象
  that = {}
  // 2. 执行构造函数
  const rtp = constructorFn.call(that, ...args)
  // 3. 判断构造函数返回值类型
  return typeof rtp === 'object' ? rtp : that

}