new 的执行过程分为四步:
- 生成新对象
- 将新对象的原型设置为构造函数的 prototype
- 将构造函数的 this 改为新对象,并执行它
- 判断构造函数的结果是否是引用类型,是则返回执行结果,不是则返回新对象
/**
* 使用构造函数和提供的参数创建一个新对象。
* @param {Function} Constructor 用于创建新对象的构造函数。
* @param {...any} args 传递给构造函数的参数。
* @returns {object} 返回新创建的对象或构造函数执行的结果。
*/
function _new(Constructor, ...args) {
// 1.生成一个新对象
const _this = {}
// 2.将新对象的原型设置为构造函数的原型对象
Object.setPrototypeOf(_this, Constructor.prototype)
// 3.将构造函数的this改为新对象,并执行它,得到执行的结果
const result = Constructor.call(_this, ...args)
// 4.判断执行的结果是否是引用类型,是则返回结果,否则返回新对象
if (
(typeof result === 'object' && result !== null)
|| typeof result === 'function'
) {
return result
}
return _this
}