学习笔记:类的基本知识

22 阅读1分钟

总结:

1.类中的构造器不是必须要写的,要对实例进行一些初始化的操作,如添加指定属性时才写。

2.如果A类继承了B类,且A类中写了构造器,那么A类构造器中的super是必须要调用的

3.类中所定义的方法,都放在了类的原型对象上,供实例去使用

// 可以不写构造器
class Person {
    speak() {
        console.log('I can speak!')
    }

}
const p1 = new Person();
p1.speak(); // Output: I can speak!
class Person {
    constructor(name, age) {
        // 构造器中的this是谁? —— 类的实例对象
        this.name = name;
        this.age = age;
    }
    
    speak() {
        // speak方法放在了哪里? —— 类的原型对象上,供实例使用
        console.log(`My name is ${this.name}, My age is ${this.age}`)
    }
}
class Student extends Person {
    constructor(name, age, grade) {
        super(name, age);
        this.grade = grade;
        this.school = 'Hogwarts';
    }
    
    // 重写
    speak() {
        console.log(`My name is ${this.name}, My age is ${this.age}`My grade is ${this.grade})
    }
}

class Person {
    constructor(name, age) {
        // 构造器中的this是谁? —— 类的实例对象
        this.name = name;
        this.age = age;
    }
}

class Student extends Person {
    constructor(name, age, grade) {
        super(name, age);
        this.grade = grade;
    }
    // 类中可以直接写赋值语句,如下所示:给Student的实例对象添加属性school和study
    school = 'Hogwarts';
    // study方法放在了哪里? —— 直接放在类的实例对象上,供实例使用
    study = () => {
        console.log(`My name is ${this.name}`)
    }
}