Class構文の基礎
sample
(function() {
'use strict';
class Country {
constructor(name) {
this.name = name;
}
greet() {
return 'Welcome to ' + this.name + '!;'
}
}
const country = new Country('Japan');
console.log(country.greet()); // ⇛ Welcome to Japan!
})();
静的メソッド static
Class構文には静的メソッドを定義することができます。
静的メソッドとはClassのインスタンスを作らずとも呼べるメソッドのことを指します。
sample
(function() {
'use strict';
class Country {
constructor() {}
static planet(obj) {
return obj;
}
}
console.log(Country.planet('地球')); // ⇛ '地球'
})();
get、setの書き方
sample
(function() {
'use strict';
class Country {
constructor() {}
get name() {
return this._name;
}
set name(name) {
this._name = name.toUpperCase();
}
}
const country = new Country();
country.name = 'japan';
console.log(country.name); // ⇛ 'JAPAN'
})();
継承について
- 「class hoge extends fuga」でhogeにfugaを継承
- 継承元のコンストラクタを呼び出すには「super()」を使う
- 継承元のメソッドを呼び出すには「super()」を使う
sample
(function() {
'use strict';
class Country {
constructor(name) {
this.name = name;
}
greet() {
return this.name + '!';
}
}
class City extends Country { // Countryを継承
constructor(name, city) {
super(name); // Countryのconstructorを継承
this.city = city;
}
greet() {
return 'I live in ' + this.city + ', ' + super.greet(); // Countryのメソッドを継承
}
}
const liveIn = new City('Japan', 'Tokyo');
console.log(liveIn.greet()); // ⇛ "I live in Tokyo, Japan!"
})();