function myNew(fn, ...args) {
//创建一个空对象
let obj = Object.create(null);
//obj.prototype==fun.__proto__
//将空对象的原型,指向构造函数的原型
Object.setPrototypeOf(obj, fn.prototype)
//改变this指向,将this指向空对象
let result = fn.apply(obj, args)
//判断该函数的是否有返回
return result ? result : obj;
}
function Test(age, name) {
this.age = age;
this.name = name;
}
const myTest = myNew(Test, 18, '张三');
console.log(myTest.name)
console.log(myTest.__proto__ === Test.prototype);
console.log(myTest instanceof Test);
function test2() {
return 2
}
const myTest2 = myNew(test2)
console.log(myTest2)