js深入之原型链继承new方法重写

147 阅读1分钟


function Dog(name) {this.name = name}
Dog.prototype.bark = function () {    console.log('wang wang')}
function _new(Fn, ...args) {    
// const obj = {}    // Object.setPrototypeOf(obj, Fn.prototype)    
const obj = Object.create(Dog.prototype)    const result = Fn.call(obj, ...args)    
return result instanceof Object ? result : obj}
const tp = _new(Dog, 'tp')
console.log(tp.name)
tp.bark()