实现 new 操作符
- 创建空白对象
- 修改空白对象的原型为构造函数的原型
- this 指向空白对象,并执行构造函数
- 返回对象
function Animal(name,age) {
this.name = name;
this.age = age;
}
function _new(constructor,...args) {
let instance = {};
// instance._proto_ = constructor.prototype; 是四个下划线
instance.__proto__ = constructor.prototype;
let result = constructor.call(instance,...args);
return typeof result === 'object'? result:instance; // 返回构造函数返回的非空对象,否则返回创建的对象
}
let a = _new(Animal,'lli','2');
console.log('a',a)
console.log(a instanceof Animal);
// expected output: true