/* 实现 new 基本原理*/ functionmyNew() { let obj = {} let Con = [].shift.call(arguments) obj.__proto__ = Con.prototype let res = Con.apply(obj, arguments) return res instanceofObject ? res : obj } /* 以下是对实现的分析: - 创建⼀个空对象 - 获取构造函数 - 设置空对象的原型 - 绑定 this 并执⾏构造函数 - 确保返回值为对象 */
1 2 3 4
function myNew(obj, ...args) { let newObj = Object.create(obj.prototype) let result = obj.apply(newObj, args) }