实现new操作符
function theNew () {
const [constructor, ...args] = arguments
if (typeof constructor !== 'function') {
throw 'first param must be a function'
}
/**
* 设置target的目的是实现es6中的new.target
*/
theNew.target = constructor
const context = Object.create(constructor.prototype)
const result = constructor.apply(context, args)
if (result && typeof result === 'object' || typeof result === 'function') {
return result
}
return context
}
/********************* test *********************/
function Boy (name, age) {
this.name = name
this.age = age
}
const boy1 = new Boy('boy1', 10)
const boy2 = theNew(Boy, 'boy2', 20)
console.log(boy1)
console.log(boy2)