クラス
ES2015(ES6)でクラスが追加されました。
クラスとは、オブジェクトを作成するためのひな形のようなものです。
オブジェクトに設定したいプロパティやメソッドを定義できます。
インスタンスとは?
インスタンスは、「 クラスをもとに生成されたオブジェクト 」を意味しています。
クラスからオブジェクトを生成する処理を「 インスタンス化 」といいます。
インスタンスとオブジェクトは同じ意味のように扱われますが、プログラミング言語や人によって、ニュアンスが違います。
クラスの作成・呼び出し
class Calc {
constructor(name, price){
this.name = name;
this.price = price;
this.tax = 0.08;
};
tax_calc(){
return this.name + ":" + this.price * this.tax;
};
};
let orange = new Calc("オレンジ", 100);
console.log(orange.tax_calc());
同じクラス内の関数を呼び出す
class Sample{
display(){
this.hello();
}
hello(){
console.log("Hello, World");
}
}
let sample = new Sample();
sample.display();
継承と委譲
継承(Inheritance) | 委譲(Delegation) |
---|---|
クラス階層 | オブジェクト間の協力 |
関係性は、「 ~は~である(is-a)」 | 関係性は、「 ~は~を使う(has-a、use-a)」 |
親クラスの機能を子が継承 | 機能を持つオブジェクトに委ねる |
固定的(階層構造) | 柔軟で動的に変更可能 |
コードの結合度は、高め(強く結びつく) | コードの結合度は、低め(疎結合) |
委譲のサンプルコードは、以下です。
class A {
speak(){
console.log("私は、ClassAです");
}
}
class B {
speak(){
console.log("私は、classBです");
}
}
class DelegationAB {
constructor(a, b) {
this.a = a; // 委譲
this.b = b; // 委譲
}
render(){
this.a.speak();
this.b.speak();
}
}
const classA = new A();
const classB = new B();
const delegationAB = new DelegationAB(classA, classB);
delegationAB.render();
クラスの継承
class Goku{
constructor(){
this.kamehameha = 10;
this.kaiouken = false;
this.magnification = 0;
this.genkidama = 30
}
act_kamehameha(){
if(this.kaiouken){
console.log("界王拳かめはめは:" + (this.kamehameha * this.magnification) + "ダメ")
} else {
console.log("かめはめは:" + (this.kamehameha) + "ダメ")
}
}
act_genkidama(){
if(this.kaiouken){
console.log("界王拳中は使えない。")
} else {
console.log("げんき玉:" + this.genkidama + "ダメ");
}
}
set_kaiouken(n){
this.kaiouken = true;
this.magnification = n;
console.log(`界王拳${n}倍`);
}
cancell_kaiouken(){
this.kaiouken = false;
this.magnification = 0;
console.log(`界王拳${0}`);
}
set_super_saiyazin(){
console.log("スーパーサイヤ人に変身した。")
return new SuperSaiyazinGoku();
}
}
class SuperSaiyazinGoku extends Goku{
constructor(){
super();
this.powerup = 300;
}
act_kamehameha(){
console.log("かめはめは(スーパーサイヤ人):" + (this.kamehameha * this.powerup) + "ダメ")
}
set_kaiouken(n){
console.log("界王拳はつかえない");
}
act_genkidama(){
console.log("げんき玉はつかえない。");
}
}
let goku = new Goku();
goku.act_kamehameha();
goku.set_kaiouken(10);
goku.act_kamehameha();
goku.cancell_kaiouken();
goku.act_kamehameha();
goku.act_genkidama();
let supersiyazingoku = goku.set_super_saiyazin();
supersiyazingoku.act_kamehameha();
supersiyazingoku.act_genkidama();