手写js new 方法

73 阅读1分钟

/**
 * new
 * 创建一个新对象
 * 改变this 指向
 * 继承构造函数的原型
 * 返回值是否 为对象 否 返回 创建的新对象
 */

function myNew(context) {
  const args = Array.prototype.shift.call(arguments); // 截取参数
  const obj = Object.create(context.prototype); // 创建一个新对象 继承原型
  const result = context.call(obj, ...args);
  return typeof result === 'object' ? result : obj; // 如果构造函数有return 且return一个引用类型, 则直接返回这个引用类型对象
}