LoginSignup
9

More than 5 years have passed since last update.

javascript の class 構文を 1/2ぐらいマスターしよう!!!

Last updated at Posted at 2018-06-07

クラス

ECMAScript 6 で導入された JavaScript クラスは、JavaScript にすでにあるプロトタイプベース継承の糖衣構文1です。クラス構文は、新しいオブジェクト指向継承モデルを JavaScript に導入しているわけではありません。JavaScript クラスは、オブジェクトを作成して継承を扱うためのシンプルで明確な構文を用意します。

基本的な構文

クラス宣言 ver.

class Square {
    constructor(width, height){
        this.width  = width;
        this.height = height;
    }
}

クラス式 ver.

名前なし
let Square = class {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
};
名前つき
let Square = class Square {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
};
注意

関数宣言では、hostingされる (関数を書く前に呼び出してもOK) が、
クラス宣言(式)では、先に呼び出すとエラーとなってしまう。

ダメな例
let s = new Square(); // Square クラスはまだ宣言されていない => ReferenceError

class Square {} // この場合ではクラス宣言だが、クラス式でも同じようにエラー

メソッド(プロトタイプメソッド)2

class Square {
    constructor(width, height){
        this.width  = width;
        this.height = height;
    }

    get area() {
        return this.getArea();
    }
    getArea() {
        return this.width * this.height;
    }
}

let s = new Square(1280, 1024);
console.log(s.area);

静的メソッド

インスタンス化なしで呼ばれる。
インスタンス化していると呼べない。

class Square {
    constructor(width, height){
        this.width  = width;
        this.height = height;
    }

    get area() {
        return this.getArea();
    }
    getArea() {
        return this.width * this.height;
    }
    static total(a, b){
        const aArea = a.area;
        const bArea = b.area;

        return aArea + bArea;
    }
}

let s1 = new Square(1280, 1024);
let s2 = new Square(1920, 1080);
console.log(Square.total(s1, s2));

拡張

class Dog {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(this.name);
    }
}

class SuperDog extends Dog {
    speak() {
        console.log('私の名前は' + this.name + ' です。\nよろしくお願いします。');
    }
}

function Dog (name) {
  this.name = name;
}
Dog.prototype.speak = function () {
  console.log(this.name);
}

class Dog extends Animal {
  speak() {
    super.speak();
    console.log('私の名前は' + this.name + ' です。\nよろしくお願いします。');
  }
}

親クラスの呼び出し

class Dog {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(this.name);
    }
}

class SuperDog extends Dog {
    speak() {
        super.speak();
        console.log('私の名前は' + this.name + ' です。\nよろしくお願いしますワン。');
    }
}

  
力尽きました。そろそろやめましょう。

参照


  1. 複雑でわかりにくい構文を、よりわかりやすく、読み書きしやすい構文として書くことのできるもの。 

  2. どのインスタンス(new してできたやつ)でも同じメソッドを使う場合に使うもの。*メソッドはコピーされるのではなく、参照される。* 

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9