手动写一个new
function MyNew(Fn, ...args) {// 新建一个对象let obj = {}// 新建对象的原型指向构造函数的原型obj.__proto__ = Fn.prototype// 绑定thislet result = Fn.apply(obj, args)// 返回return result instanceof Object ? result : obj
}
测试一下:
function Person(name, age) {this.name = namethis.age = age
}
Person.prototype.say = function() {console.log(`Hi, My name is ${this.name}, and my age is ${this.age}`)
}let person = MyNew(Person, 'huihiui', 15)
console.log(person.name, person.age)
person.say()