1.ES6之后通过extends继承父类的属性和方法。
// 父类
class Parent {
constructor(name, age, weight) {
this.name = name
this.age = age
this.weight = weight
}
work() {
console.log('parent can work.');
}
}
let papa = new Parent('Bob', 50)
papa.work()// parent can work.
console.log(papa.name);// Bob
console.log(papa.age);//0
//子类
class Son extends Parent {
constructor(name, age, weight, height) {
super(name, age, weight)
this.name = name
this.height = height
}
study() {
console.log('No pain, no gain.');
}
}
let child = new Son('Tommy', 12, 40, 155)
child.work() //parent can work. //子类继承了父类的方法
child.study() //No pain, no gain. //子类调用了自己的方法
console.log(child.weight);//40 //继承了父类的weight属性
console.log(child.name);//Tommy
2.ES6前使用构造函数+原型对象来实现继承,也称为组合继承。
//父类
function Parent(name, age) {
this.name = name
this.age = age
}
Parent.prototype.work = function () { //父类上的一个方法
console.log('parent can work');
}
//子类
function Child(name, age) {
Parent.call(this, name, age) //call方法改变了this的指向(指向了son),也调用了Parent构造函数
}
//继承父类的方法
Child.prototype = new Parent()
Child.prototype.constructor = Child
let son = new Child('tommy', 12)
// console.log(son.name);// tommy
// console.log(son); //Child {name: 'tommy', age: 12} //拥有了父类的属性
son.work()//parent can work //继承到了父类的方法