JavaScriptのクラス
class構文・・・
コンストラクタやメソッドを簡単に定義できるものになります。
コンストラクタはインスタンス(実体)を作成する関数、メソッドはオブジェクトの中に
定義される関数です。
つまりclass構文は、色々な関数をひとまとめにして、使い回せるようにできるようにな
ります。
そしてclass構文は、他のclass構文に内容を引き継ぐことができます。
もともと書かれている構文をいじらなくても内容の追加などを行なうことも可能となります。
・クラス宣言の仕方
クラス名は大文字で記述します。
実際に記述してみます。
class Color {
constructor(r, g, b) {
〜〜〜記述する処理〜〜〜
}
}
まず、constructor関数を記述します。
この関数は、クラスのオブジェクトが新しく作成される時に必ず自動的に呼ばれる関数となります。
コンストラクタ関数で記述したコードをクラスを用いて書き直してみます。
class Color {
constructor(r, g, b, name) {
this.r = r;
this.g = g;
this.b = b;
this.name = name;
}
}
//インスタンスを生成
const c1 = new Color(255, 67, 89, 'tomato');
それぞれの値が設定されているのが確認取れます。
・メソッドの定義の仕方
4つのメソッドを定義してみました。これらのメソッドは「Color」のプロトタイプに定義されるようになります。
前回まで
Color.prototype.rgb = function ()
今回(直接Colorの一員として書けます)
class Color {
constructor(r, g, b, name) {
this.r = r;
this.g = g;
this.b = b;
this.name = name;
}
innerRGB() {
const { r, g, b } = this;
return `${r},${g},${b}`;
}
rgb() {
return `rgb(${this.innerRGB()})`
}
rgba(a = 1.0) {
return `rgba(${this.innerRGB()}, ${a})`
}
hex() {
const { r, g, b } = this;
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
}
//インスタンスを生成
const red = new Color(255, 67, 89, 'tomato');
const white = new Color(255, 255, 255, 'white');
下記のようにインスタンスを生成した際にメソッド名を記述するだけで処理を実行できます。
white.hex();
red.rgba();