手写系列 - new

108 阅读1分钟
function _new(obj, ...rest) {
  // 基于obj的原型创建一个新的对象
  const newObj = Object.create(obj.prototype);

  // 添加属性到新创建的newObj上, 并获取obj函数执行的结果.
  const res = obj.apply(newObj, rest);

  // 如果执行结果有返回值并且是一个对象, 返回执行的结果, 否则, 返回新创建的对象
  return res instanceof Object ? res : newObj;
}

function Person(name, age) {
  this.name = name
  this.age = age;

}

Person.prototype.sayName = function () {
  console.log(this.name);
}


let p = _new(Person, "zhongleiyang", 22)
console.log(p) //Person { name: 'zhongleiyang', age: 22 }
p.sayName() // zhongleiyang