function myNew(func, ...args) { // 创建一个新对象,并链接到构造函数的 prototype 上 const newObj = Object.create(func.prototype); // 调用构造函数,并将新对象作为 this 传入 const result = func.apply(newObj, args); // 如果构造函数返回了一个对象,则返回该对象,否则返回新对象 return result instanceof Object ? result : newObj; }

JavaScript 实现简单的自定义 new 函数

原文地址: https://www.cveoy.top/t/topic/m74q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录