需要注意的点:
1.return一个引用数据类型时,new的新对象是该引用类型对象
2.过程:创建一个空对象,绑定构造函数的原型prototype。再执行构造函数,得到result。
代码
function myNew(Fn, ...args) {
const child = {};
Object.setPrototypeOf(child, Fn.prototype);
const result = Fn.call(child, ...args)
return (typeof result === 'object' || typeof result === 'function') && result ? result : child
}
测试
测试原型方法
function Fun(c) {
this.a = 10;
this.b = 20
return c
}
Fun.prototype.method = function () {
console.log('原型上的method被访问');
}
const fun1 = new Fun(1);
console.log(fun1.method());
const fun2 = myNew(Fun, 1)
console.log(fun2.method());
测试返回引用数据类型
function Fun(c) {
this.a = 10;
this.b = 20
return c
}
Fun.prototype.method = function () {
console.log('原型上的method被访问');
}
const fun1 = new Fun([1]);
console.log(fun1);
const fun2 = myNew(Fun, [1])
console.log(fun2);
测试返回基本数据类型
function Fun(c) {
this.a = 10;
this.b = 20
return c
}
Fun.prototype.method = function () {
console.log('原型上的method被访问');
}
const fun1 = new Fun(1);
console.log(fun1);
const fun2 = myNew(Fun, 1)
console.log(fun2);
记录记录!