- 类中的构造器不是必须写的,要对实例进行一些初始化的操作,如添加指定属性时才写。
- 如果A类继承了B类,且A类中写了构造器,那么A类构造器中super是必须要调用的
- 类中所定义的方法,都是放在了类的原型对象上,供实例去使用
<body>
<div id="app">
</div>
<script type="text/babel">
// 创建一个Person 类
class Person {
//构造器方法
constructor(name, age) {
this.name = name
this.age = age
// this 是指类的实例对象
}
// 方法
speak() {
//speak 这个方法在Person 类的原型对象里面 供实例使用
// 通过Person实例调用speak时,spean中this就是Person实例
console.log('我叫' + this.name + '我的年龄是' + this.age)
}
}
//创建一个student类,继承于Person类
class Student extends Person {
//构造器方法
constructor(name, age, grade) {
super(name, age) // super 调用父级的name和age
this.grade = grade
}
//重写从父类继承过来的方法
speak() {
console.log('我叫' + this.name + '我的年龄是' + this.age + this.grade + '年级')
}
study() {
// study 方法放在了类的原型对象上,供实例使用
// 通过Student实例调用study时,study中的this就是student实例
console.log('我在学习')
}
}
//创建一个Person的实例对象
const p1 = new Person('tom', 18)
const p2 = new Person('lisa', 19)
console.log(p1) //Person {name: "tom", age: 18}
console.log(p2) // Person {name: "lisa", age: 19}
p1.speak() //Inline Babel script:14 我叫tom我的年龄是18
p2.speak() //我叫lisa我的年龄是19
// 建立一个Student的实例
const s1 = new Student('lisa', '5','幼儿园')
console.log(s1) //IStudent {name: "lisa", age: "5"}
s1.study()
</script>
</body>
</html>