constructor 的含义

constructor 是一种用于创建和初始化class创建的对象的特殊方法。

在一个类中只能有一个constructor方法,本质是一个构造函数,如果一个类不指定一个构造函数(constructor)方法, 则使用一个默认的构造函数(constructor)。
示例代码:
首先声明一个 People 类

class People{
  constructor(sex,age) {
    this.name = 'xiao fan';
    this.sex = sex;
    this.age = age;
  }
}

const people1= new People();

console.log(people1.name);
// expected output: "xiao fan"
class Student extends People{
    constructor(sex,age) {
      
        // 在这里, 它调用了父类的构造函数,  提供给 People 的"sex"和"age"
        super(sex, age);
        // 注意: 在派生类中, 必须先调用 super() 才能使用 "this"。
        // 忽略这个,将会导致一个引用错误。
        this.name = 'xiao hua';
        this._info = this.name+' ' + this.sex+' ' + this.age;
    }
    get info() {
        return this._info;
    }
    set info(value) {
        // 注意:不可使用 this.info= value
        // 否则会导致循环call setter方法导致爆栈
        this._info = value;
    }

};

实例化 student

const  student = new Student('男',15);
//get方法
console.log(student.info)
// expected output: "xiao hua 男 15"
const  student = new Student('男',15);
//set方法
student.info = '123'
console.log(student.info)
// expected output: "123"
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐