Blog
Blog copied to clipboard
原型与原型链 - new的详细过程及其模拟实现
new的详细过程及其模拟实现
new
一个对象的详细过程
- 创建一个全新对象,并将该对象原型指向构造函数的原型对象;
- 将构造函数调用的this指向这个新对象,并执行构造函数;
- 如果构造函数执行结果为对象类型(包含Object,Functoin, Array, Date, RegExg, Error等),则返回执行结果,否则返回创建的新对象。
模拟实现new
function newOperator(Ctor, ...args) {
if (typeof Ctor !== 'function') {
throw new TypeError('First argument is not a constructor')
}
// 1. 创建一个全新对象,并将该对象原型指向构造函数的原型对象
const obj = Object.create(Ctor.prototype)
// 2. 将构造函数调用的this指向这个新对象,并执行构造函数;
const result = Ctor.apply(obj, args)
// 3. 如果构造函数执行结果为对象类型,则返回执行结果,否则返回创建的新对象
return (result instanceof Object) ? result : obj
}