LoginSignup
11
17

More than 5 years have passed since last update.

ES6のClassの書き方をまとめてみた

Last updated at Posted at 2017-08-18

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!"
})();

参考サイト

11
17
0

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
11
17