JS模拟 new 操作符

new 操作符用于创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。

function Person(name, age, sex) {
   this.name = name;
   this.age = age;
   this.sex = sex;
}

var lilei = new Person('Lilei', 21, '男');

 

模拟new操作过程的函数:

function _new(_constructor) {
  // 1. 创建一个空的简单JavaScript对象
  var obj = {};
  // 获取要传入构造器中的参数
  var args = [].slice.call(arguments, 1);
  // 2. 将被创建对象的__proto__指向构造函数的prototype;
  obj.__proto__ = _constructor.prototype;
  // 3. 将被创建对象作为this的上下文(并获取执行结果)
  var res = _constructor.apply(obj, args);
  // 4. 返回构造函数的返回值或当前被创建的对象
  return res && (typeof res === 'object' || typeof res === 'function') ? res : obj;
}

或者(利用新的api)

function _new(_constructor, ...args) {
  // 基于构造器的原型创建一个新对象
  const obj = Object.create(_constructor.prototype);
  // 获取基于obj调用_constructor的执行结果
  const res = _constructor.apply(obj, args);
  return res && (typeof res === 'object' || typeof res === 'function') ? res : obj;
}

 

使用实例:

function A() {}

var a = _new(A, /* A的函数入参 */)

 

End

posted @ 2022-04-19 09:51  樊顺  阅读(86)  评论(0编辑  收藏  举报