class Person {
constructor(name, age) {
// 构造器中的 this 是类的实例对象
this.name = name
this.age = age
}
speak() {
// speak 方法放在了类的原型对象上,供实例使用
// 通过 Person 实例调用 speak 时,speak中的 this 就是 Person 实例
console.log(`my name is ${this.name}, my age is ${this.age}`)
}
}
/*
const p1 = new Person('tony', 20)
const p2 = new Person('jack', 18)
console.log(p1)
console.log(p2)
p1.speak()
p2.speak()
*/
class Student extends Person {
constructor(name, age, grade) {
super(name, age)
this.grade = grade
}
speak() {
console.log(`my name is ${this.name}, my age is ${this.age}, my grade is ${this.grade}`)
}
study() {
console.log('I love study')
}
}
const s1 = new Student('bob', 16, 'three')
console.log(s1)
s1.speak()
s1.study()
javascript 类的基础知识
geekymv 发表于:2024-08-11 04:02:03 阅读数:306