关于new操作符的分析
1. new的执行步骤
- 生成一个新的object.
- 将构造函数的上下文指向object.
- 当构造函数返回值是基本数据类型时返回object,否则返回原始返回值。
2. 代码
function _new(fun,args){
let o = Object.create(fun.getPrototypeOf());
let res = fun.apply(o,args);
return res instanceof Object?res:o;
}
这里需要注意,res如果是基本类型则返回o否则返回res,这是和原始new操作符的逻辑一致的。虽然很奇怪。