一、new的时候内部做了什么?
- 首先在内存中创建一个新对象。
- 然后将新对象的____proto____赋值为构造函数的 prototype 属性。
- 将构造函数内部的 this 被赋值为刚刚创建的新对象。
- 执行构造函数。
- 如果构造函数返回非空对象,则返回该对象。否则返回 this。
二、实现代码
function myNew(...args) {
//1.创建一个对象
var obj = Object.create(null);
//2.将对象的原型指向构造函数
const constructor = args.shift(); //第一个参数就是构造函数
obj.__proto__ = constructor.prototype;
//3.调用构造函数
let res = constructor.apply(obj, args);
//4.根据构造函数返回值决定返回内容,若构造函数返回非空对象,则返回这个对象,否则返回this
return typeof res === "object" && res !== null ? res : obj;
}
运用
function myfun(name, age) {
this.name = name;
this.age = age;
}
var bar = myNew(myfun, "zs", 12);
console.log(bar.name, bar.age);//zs 12