new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。new 关键字会进行如下的操作
- 创建一个空的简单JavaScript对象(即{});
- 链接该对象(即设置该对象的构造函数)到另一个对象 ;
将步骤1新创建的对象作为this的上下文 ;
- 如果该函数没有返回对象,则返回this。
function _new(Ctor, ...args) {// 创建一个空的简单JavaScript对象let o = Object.create(null);if(Ctor.prototype !== null) {// 链接该对象(即设置该对象的构造函数)到另一个对象// o.__proto__ = Ctor.prototype// 等同于o = Object.create(Ctor.prototype)}// 将步骤1新创建的对象作为this的上下文let result = Ctor.apply(o, args);// 如果该函数没有返回对象,则返回this。if ((typeof result === 'function' || typeof result === 'object')&& typeof result !== 'null') {return result;}return o;}
