JavaScript class继承

JavaScript class继承教程

在 ES6 中引入了 class 关键字,class 可以通过 extends 关键字实现 继承,还可以通过 static 关键字定义类的静态方法,这比 ES5 的通过修改 原型链 实现继承,要清晰和方便很多。

ES5 的继承,实质是先创造子类的实例对象 this,然后再将父类的方法添加到 this 上面(Parent.apply(this))。ES6 的继承机制完全不同,实质是先将父类实例对象的 属性方法,加到 this 上面(所以必须先调用 super 方法),然后再用子类的构造函数修改 this。

需要注意的是,class 关键字只是原型的语法糖,JavaScript 继承仍然是基于原型实现的。

JavaScript class继承优缺点

优点

  • 语法简单易懂,操作更方便。

缺点

  • 并不是所有的浏览器都支持 class 关键字。

JavaScript class继承详解

语法

class Object1 { //调用类的构造方法 constructor(attr1, attr2) { this.attr1 = attr1; this.attr2 = attr2; } } class Object2 extends Object1 { constructor(attr1, attr2, attr3) { super(attr1, attr2); //通过super调用父类的构造方法 this.attr3 = attr3; } }

说明

我们通过 ES6 中的 class 加上 extends 实现了继承。

案例

JavaScript class继承详解

通过 class 加上 extends 实现了继承

<!DOCTYPE html> <html> <head> <title>JavaScript class 加上 extends 实现了继承</title> <script type="text/javascript"> console.log("嗨客网(www.haicoder.net)"); class Person{ constructor(name, age) { this.name = name; this.age = age; } info(){ console.log("Person name =", this.name, "age =", this.age); } } class Student extends Person{ constructor(name, age, score) { super(name, age); //通过super调用父类的构造方法 this.score = score; } info(){ console.log("Student name =", this.name, "age =", this.age, "score =", this.score); } } var p = new Person("haicoder", 109); var stu = new Student("HaiCoder", 110, 99); console.log("Person =", p); console.log("Student =", stu); p.info(); stu.info(); </script> </head> </html>

程序运行后,控制台输出如下:

45_JavaScript继承.png

我们通过 class 定义了一个类,接着,我们通过 extends 关键字实现了类的继承。

JavaScript class继承总结

在 ES6 中引入了 class 关键字,class 可以通过 extends 关键字实现继承,还可以通过 static 关键字定义类的静态方法,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。