ES 6人学習整理(八)——Class
4151 ワード
構文
基本構文の例
// Person.js
export default class {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
setName(name) {
this.name = name;
}
getAge() {
return this.age;
}
setAge(age) {
this.age = age;
}
say() {
return `My name is ${this.name}, I'm ${this.age} years old!`;
}
}
// test.js
import Person from './Person';
let person = new Person('Zhang San', 18);
person.getName(); // Zhang San
person.getAge(); // 18
person.setName('Li Si');
person.getName(); // Li Si
person.setAge(19); // 19
person.say(); // My name is Li Si, I'm 19 years old!
// js Java
継承
// Student.js
import Person from './Person';
export default class extends Person {
constructor(name, age, teacher) {
super(name, age);
this.teacher = teacher;
}
getTeacher() {
return this.teacher;
}
setTeacher(teacher) {
this.teacher = teacher;
}
say() {
return `My name is ${this.name}, I'm ${this.age} years old, and my teacher is ${this.teacher}!`;
}
}
// test.js
import Student from './Student';
let student = new Student('Zhang San', 19, 'Mr Tian');
student.say(); // My name is Zhang San, I'm 19 years old, and my teacher is Mr Tian!
// java, ,
// , , ~~
スタティツクメソッド
クラス内のメソッドの前にstaticキーワードを追加します.このメソッドはインスタンスに継承されず、クラスのみで呼び出されます(サブクラスで直接クラス名でアクセスできます).静的メソッドと呼ばれます.
// Person.js
export default class {
static test() {
return 'Test static method';
}
}
// Student.js
import Person from './Person';
Person.test();
export default class extends Person {
say() {
Person.test();
}
}