精简版
class Child {
constructor(){
//待用父类的构造函数
Parent.call(this)
// 利用object.Create生成一个对象 新生成的对象是父级的原型parent.prototype 并将该对象作为子类构造函数的原型 继承了父类原型上的属性和方法
Child.prototype = Object.create(Parent.prototype)
//原型对象的construstor指向子类的构造函数
Child.prototype.constructor = Child
}
}
通用版
function Parent(name){
this.name = name
}
Parent.prototype.say = function(){
console.log(this.name)
}
function Child(name,age){
Parent.call(this,name)
this.age = age
}
// Child.prototype = Parent.prototype
function createoBJ (O){
// 目的为了继承父类原型上的属性和方法 在不需要实例化父类构造函数的情况下 避免生成父类的实例
function F(){
}
F.prototype = O
// 创建一个空对象 该对象的原型指向父类的原型对象
return new F()
}
// 这一不等同于Child.prototype = Object.create(Parent.prototype)
Child.prototype = createoBJ(Parent.prototype)
Child.prototype.constructor = Child
let p = new Child('tom',78)
console.log(p)
p.say()