function _new(constructor, ...args) {
// 1. 验证 constructor 是不是一个函数
if (typeof constructor !== 'function') {
return new TypeError('constructor is not a function');
}
// 2. 创建一个对象,使用 Object.create 将新对象的原型链指向了构造函数的原型,保证了新对象能够访问到构造函数原型上的属性和方法
const obj = Object.create(constructor.prototype);
// 3. 将 this 指向 obj
const result = constructor.apply(obj, args)
// 4. 如果 result 是对象则返回,不是则返回 obj
return result instanceof Object ? result : obj;
}
// 构造函数无返回值
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`Hello, I'm ${this.name}`);
};
const person = _new(Person, 'Alice');
person.sayHello(); // 输出: "Hello, I'm Alice"
console.log(person instanceof Person); // true
// 构造函数有返回值
function Car() {
return { color: 'red' };
}
const car = _new(Car);
console.log(car); // 输出: { color: 'red' }
console.log(car instanceof Car); // false(因为返回的是新对象,而非 Car 实例)
// 构造函数返回基本类型
function Bike() {
return 'blue';
}
const bike = _new(Bike);
console.log(bike); // 输出: Bike {}(返回新对象,忽略基本类型返回值)
console.log(bike instanceof Bike); // true