Skip to content

Instantly share code, notes, and snippets.

@kajirikajiri
Last active June 13, 2020 11:59
Show Gist options
  • Save kajirikajiri/525aed3092e555b40b2db4c6da1a59ee to your computer and use it in GitHub Desktop.
Save kajirikajiri/525aed3092e555b40b2db4c6da1a59ee to your computer and use it in GitHub Desktop.
JavaScript class

using super in classes

class Rectangle {
  constructor(height, width) {
    this.name = 'Rectangle';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }
  get area() {
    return this.height * this.width;
  }
  set area(value) {
    this.height = this.width = Math.sqrt(value);
  }
}

class Square extends Rectangle {
  constructor(length) {
    this.height; // ReferenceError になります。super を先に呼び出さなければなりません!

    // length の値で親クラスの constructor を呼びます。
    // Rectangle の width と height になります。
    super(length, length);

    // Note: 'this' を使う前に super() をコールしなければなりません。
    // でないと reference error になります。
    this.name = 'Square';
  }
}

親のコンストラクターを読んで上書きできる

call super in static methods

class Rectangle {
  constructor() {}
  static logNbSides() {
    return 'I have 4 sides';
  }
}

class Square extends Rectangle {
  constructor() {}
  static logDescription() {
    return super.logNbSides() + ' which are all equal';
  }
}
Square.logDescription(); // 'I have 4 sides which are all equal'

親の関数をstaticメソッド内部でsuperを通じて呼び出すことができる

using super.prop in Object ritelal

var obj1 = {
  method1() {
    console.log('method 1');
  }
}

var obj2 = {
  method2() {
    super.method1();
  }
}

Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"
obj2.method1() // これでも呼べる

prototypeのメソッドをsuperを使うことで呼び出すことができる。

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/super

static

static キーワードは、クラスに静的メソッドを定義します。静的メソッドはクラスのインスタンスから呼び出されません。その代わりに、静的メソッドはクラスそのものから呼び出します。これらは多くの場合、オブジェクトの生成や複製を行う関数などの、ユーティリティ関数です。

インスタンスからはよべない。

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes/static

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment