# 描述new一个对象的过程
建议阅读《面试官问:能否模拟实现JS的new操作符》 (opens new window)
基础流程是:
- 创建了一个全新的对象。
- 这个对象会被执行[[Prototype]](也就是__proto__)链接。
- 生成的新对象会绑定到函数调用的this。
- 通过new创建的每个对象将最终被[[Prototype]]链接到这个函数的prototype对象上。
- 如果函数没有返回对象类型Object(包含Functoin, Array, Date, RegExg, Error),那么new表达式中的函数调用会自动返回这个新的对象。
具体代码实现如下:
function myNew(ctor){
if(typeof ctor !== 'function'){
throw 'myNew function the first param must be a function';
}
myNew.target = ctor;
const newObj = Object.create(ctor.prototype);
const argsArr = [].slice.call(arguments, 1);
// 如果代码返回内容是object或function,则直接返回结果,否则返回新创建的对象
const res = ctor.apply(newObj, argsArr);
const isObject = typeof res === 'object' && res !== null;
const isFunction = typeof res === 'function';
if(isObject || isFunction){
return res;
}
return newObj;
}