说明
ES6 从入门到精通系列(全23讲)学习笔记。
类的继承
使用关键字 extends
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 父类 class Animal { constructor(name, age) { this.name = name; this.age = age; } getName() { return this.name; } getAge() { return this.age; } } // 子类继承父类 class Dog extends Animal { constructor(name, age, color) { // 这里的super(name, age) 等价于 Animal.call(this, name, age) super(name, age); this.color = color; } // 子类的方法 getColor() { return `它的颜色是${this.color}`; } // 重写父类方法 getName() { return `${this.name}今年${super.getAge()}岁,它的颜色是${this.color}`; } } let d = new Dog("小黑", 3, "白色"); console.log(d); console.log(d.getColor()); console.log(d.getAge()); console.log(d.getName()); </script> </body> </html>