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 @   樊顺  阅读(93)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示