基于原型的继承
1、父类
function Animal(name) {
this.name = name
}
Animal.prototype.echoName = function () {
console.log(this.name);
}
2、子类
function Dog(name, age) {
Animal.call(this, name)
this.age = age
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.sayHello = function () {
console.log(this.name, this.age);
}
3、实例化
var animal = new Animal('Tom')
animal.echoName()
var dog = new Dog('Tom', 23)
dog.echoName()
dog.sayHello()
基于class的继承
1、父类
class Animal {
constructor(name) {
this.name = name
}
echoName() {
console.log(this.name);
}
}
2、子类
class Dog extends Animal {
constructor(name, age) {
super(name)
this.age = age
}
sayHello() {
console.log(this.name, this.age);
}
}
3、实例化
var animal = new Animal('Tom')
animal.echoName()
var dog = new Dog('Tom', 23)
dog.echoName()
dog.sayHello()