new的原理
let obj = {};
obj. proto = Fn.prototype;
Fn.call(obj);
新建一个空对象;
将对象的原型proto指向构造函数的prototype
将函数的this指针指向新对象 并调用函数;
手写一个new
关键点是使用proto或Object.create()继承函数原型和方法,并将this指向新建的对象
function myNew () {
let obj = {};
// arguments的第一个值为构造函数
const constructor = Array.prototype.shift.call(arguments);
const args = arguments;
obj.__proto__ = constructor.prototype;
constructor.call(obj, ...args);
return obj;
}
// Fn是构造函数,args为参数
let newObj = myNew(Fn, args);