js之new一个对象原理
一、new实现
function _new() { let obj= {}; // 创建的新对象 // 第一个参数是构造函数 let [constructor, ...args] = [...arguments]; // 存取构造函数原型 obj.__proto__ = constructor.prototype; // 使用apply在obj作用域中调用构造器函数,属性和方法被添加到 this 引用的对象即obj中 let result = constructor.apply(obj, args); if (result && (typeof (result) == "object" || typeof (result) == "function")) { // 如果构造函数执行的结果返回的是一个对象或者函数,那么返回这个对象或者函数 return result; } // 如果构造函数返回的不是一个对象或者函数,我们就返回创建的新对象 return obj; }
二、测试
function Person(name, age) { this.name = name; this.age = age; return 123; } // new Person('tom', 18) 相当于 _new(Person, 'tom', 18) console.log('_new', _new(Person, 'tom', 18)); // {name: 'tom', age: 18} console.log('new', new Person('tom', 18)); // {name: 'tom', age: 18}
参考:
https://www.jianshu.com/p/517a33adc0eb
------smile