js - new操作符

477 阅读1分钟

new操作符

新对象通过使用 new 操作符后跟一个构造函数(constructor)来创建。构造函数就是用来创建新对象的函数,比如下面这行代码:

let now = new Date();

使用 new 调用类的构造函数会执行如下操作

  1. 在内存中创建一个新对象。
  2. 这个新对象内部的[[Prototype]]指针被赋值为构造函数的 prototype 属性。
  3. 构造函数内部的 this 被赋值为这个新对象(即 this 指向新对象)。
  4. 执行构造函数内部的代码(给新对象添加属性)。
  5. 如果构造函数返回非空对象,则返回该对象;否则,返回刚创建的新对象。

手动创建

  • 创建了一个全新的对象【这个对象会被执行[[Prototype]](也就是__proto__)链接,通过new创建的每个对象将最终被[[Prototype]]链接到这个函数的prototype对象上】。
  • 生成的新对象会绑定到函数调用的this,执行函数。
  • 如果函数没有返回对象类型Object(包含Functoin, Array, Date, RegExg, Error),那么new表达式中的函数调用会自动返回这个新的对象。
function newOperator(ctor) {
  if (typeof ctor !== 'function') {
    throw new TypeError(' first param is not a function'); 
  }

  let obj = Object.create(ctor.prototype);
  
  let argsArray = Array.prototype.slice.call(arguments, 1);
  var returnValue = ctor.apply(obj, argsArray);
  var isObject = typeof returnValue === 'object' && returnValue !== null;
  var isFunction = typeof returnValue === 'function';
  
  if (isObject || isFunction) return returnValue;
  return obj;
}