fat-cat

new 运算符: 创建一个用户定义的兑现类型的实例,或具有构造函数的内置兑现的实例


new 关键字会进行如下的操作:

MDN 版:


 function _new(func) {
   var obj = {};
   if(func.prototype !== null) obj.__proto__ = func.prototype;

   var params = Array.prototype.slice.call(arguments, 1); // arguments :[func, ...rest]
   var ret = func.apply(obj, params);
   if(['object', 'function'].includes(typeof ret) && ret !== null) return ret;

   return obj;
 }

 function A() {}

 var instanceA1 = _new(A, 1, 2);
 var instanceA2 = new A(1, 2);
 console.log(instanceA1 instanceof A) // true
 console.log(instanceA2 instanceof A) // true

举个栗子

 function A() {
   this.a = 1 // 执行A(), 这里的 this 指向的是 window

   return {
     b: 2,
     c: 3
   }
 }

 A.prototype.a = 4
 A.prototype.b = 5
 A.prototype.c = 6

 const x = new A()

 console.log(x.a, x.b, x.c) // undefined, 2, 3