需要实现的效果如下:
function Dog(name){
this.name = name
}
Dog.prototype.bark = function(){
console.log('wangwang');
}
Dog.prototype.sayName = function(){
console.log('my name is '+ this.name);
}
let sanmao = _new(Dog, '三毛')
sanmao.bark()
sanmao.sayName()
new方法主要做了四件事:
- 新建一个空对象;
- 把新对象的原型指向构造函数的原型;
- 把构造函数内部的
this 指向这个空对象;
- 执行构造函数, 返回结果是函数或对象返回, 否则返回空对象.
function _new(Func, ...args){
let obj = Object.create(Func.prototype)
let result = Func.call(obj, ...args)
if(result !== null && /^(object|function)$/i.test(typeof result)) return result
return obj
}