剖析 js 中 constructor
constructor 的含义constructor 是一种用于创建和初始化class创建的对象的特殊方法。在一个类中只能有一个constructor方法,本质是一个构造函数,如果一个类不指定一个构造函数(constructor)方法, 则使用一个默认的构造函数(constructor)。示例代码:首先声明一个 People 类class People{constructor(sex,age) {
·
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"
更多推荐
已为社区贡献2条内容
所有评论(0)