new的重写
Function.prototype.new = function () {
const fn = this;
const obj = Object.create(fn.prototype);
const res = fn.apply(obj, arguments);
return res instanceof Object ?res : obj;
};
// 测试
function Person(name, sex, age) {
this.name = name;
this.age = age;
this.sex = sex;
// return '123';
// return {}
}
const p1 = Person.new("张三", '男', 19)
const p2 = Person.new("李四", '女', 18)
const p3 = Person.new("王五", '男', 20)
console.log(p1);
console.log(p2);
console.log(p3);