观察
观察new的结果,rec1是一个对象,对象被赋予了构造函数的属性,并根据传参赋予属性相应的值。并且rec1的[[prototype]]指向的是构造函数Rectangle,因此rec1是Rectangle的实例
function Rectangle (width,height) {
this.width = width;
this.height = height;
}
const rec1 = new Rectangle(200,100);
console.log(rec1);
// { width:200, height:100, __proto__: Rectangle }
console.log(rec1 instanceof Rectangle);
// true
实现返回一个对象
- 先声明一个空对象
- 然后调用改造函数,并修改this指向为obj(call,apply)
- 返回这个对象
这一步只是实现了返回对象,对象的原型链指向并不对
function Rectangle (width,height) {
this.width = width;
this.height = height;
}
function fakeNew (func,width,height){
let obj = {}; // 1
func.call(obj,width,height); // 2
return obj;// 3
}
const rec2 = fakeNew(Rectangle,200,100);
console.log(rec2);
// { width:200, height:100, __proto__: Object }
console.log(rec2 instanceof Rectangle);
// false
修改原型链
function Rectangle (width,height) {
this.width = width;
this.height = height;
}
function fakeNew (func,width,height){
let obj = {}; // 1
func.call(obj,width,height); // 2
Object.setPrototypeOf(obj,func.prototype);// 修改原型链
return obj;// 3
}
const rec2 = fakeNew(Rectangle,200,100);
console.log(rec2);
// { width:200, height:100, __proto__: Rectangle }
console.log(rec2 instanceof Rectangle);
// true