class的继承
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>class 的繼承</title>
</head>
<body>
<script>class Person {constructor (name, age, gender) {this.name = namethis.age = agethis.gender = genderthis.type = 'human'}sayHello () {window.alert('hello ' + this.name)}}// class 可以使用 extends 關鍵字實現對父類的繼承// 不僅可以繼承屬性,還可以繼承父類的原型方法// 這里繼承的本質是使用的:原型式繼承// 注意:在子類中,如果沒有寫 constructor 則不需要調用 super// 如果一旦寫了 constructor ,就必須手動調用一下 super 父類構造函數,否則報錯class Student extends Person {constructor (name, age, gender, id) {// super 就父類構造函數// 借用父類構造函數,把 name、age、gender 初始化到 Student 實例中super(name, age, gender)this.id = id}study () {console.log(this.name + ' 在學習。。。')}}class Teacher extends Person {constructor (name, age, gender) {// super 就父類構造函數// 借用父類構造函數,把 name、age、gender 初始化到 Student 實例中super(name, age, gender)}teaching () {console.log(this.name + ' 在上課。。。')}}const s1 = new Student('張三', 18, '男')
</script>
</body>
</html>
?
總結