首先搞明白 new 方法做了一件什么事?
function People(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
People.prototype.fullName = function () {
return `${this.firstName} ${this.lastName}`
}
const thinc = new People('first-name', 'last-name')
console.log(thinc);
简单来说就是隐式创建和返回了 this 对象
function People(firstName, lastName) {
// 隐式创建
// this = {}
this.firstName = firstName
this.lastName = lastName
// 隐式返回
// return this
}
具体点分为三步:
- 创建一个新对象
- 添加父类(People)的属性和方法到新对象中,继承父类原型上的属性和方法
- 如果执行结果有返回值,则返回执行结果;否则返回新创建的对象
代码
function _new(obj, ...rest){
// 基于obj的原型创建一个新的对象
// 在 prototype 上定义公共属性和方法
const newObj = Object.create(obj.prototype);
// 添加属性到新创建的 newObj 上, 并获取 obj 函数执行的结果.
const result = obj.apply(newObj, rest);
// 如果执行结果有返回值并且是一个对象, 返回执行的结果, 否则, 返回新创建的对象
return result instanceof Object ? result : newObj;
}