ES6(ES2015)から javascript でも Class が使えるようになりました。
この記事では、Classの使い方を紹介します。
クラス宣言
クラスを宣言して使います。
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } } const rectangle = new Rectangle(10, 10); console.log(rectangle); //{ height: 10, width: 10 }
クラス式
クラスを使う方法は上記の宣言のほかに、式があります。クラス式を定義して使います。
let Rectangle = class { //let Rectangle = class Rectangle{ このように書いても同じ constructor(height, width) { this.height = height; this.width = width; } }; const rectangle = new Rectangle(10, 10); console.log(rectangle); //{ height: 10, width: 10 }
constructor
constructorメソッドは初めに呼ばれる特別なメソッドです。
次のように記載しておくと、Rectangleをインスタンス化した際の2つの引数がconstructorメソッドに渡されます。
class Rectangle { constructor(height, width) { ・・・
Javaとは少々書き方が異なりますが、概念としては同じですね。
static
メンバーやクラスにstatic修飾子を付けることが出来ます。static修飾子を付けると、インスタンス化(new)しなくてもメンバーやクラスを使用することが出来ます。
これはJavaと同様ですね。
extends
クラスにextendsを付けて、継承させることも出来ます。
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } class Dog extends Animal { constructor(name) { super(name); // スーパークラスのコンストラクターを呼び出し、name パラメータを渡す } speak() { console.log(`${this.name} barks.`); } } let d = new Dog('Mitzie'); d.speak(); // Mitzie barks.
これもJavaと同じですね。
以上、「javascript で Class を使う方法」でした。