LoginSignup
0
0

More than 3 years have passed since last update.

JavaScriptのclassについて学んだことメモ(随時追記)

Posted at

オブジェクト指向プログラミングにあこがれ、JavaScriptのclassを勉強しているので発見をメモ。随時追記します。

コンストラクタ

コンストラクタはクラスからインスタンスを生成したときに実行される関数。
平たく言えば"関数"なので関数でできることはだいたいできる。

定数・変数を定義

js
class Hoge {
  constructor() {
    const a = 'AAA';
    console.log(a); 
  }
}

const hoge = new Hoge(); // AAA

コンストラクタ内で定義した定数・変数はコンストラクタ内でしか使えない。
コンストラクタの外、例えばメソッドでつかったり、インスタンス化したあとインスタンスプロパティとして呼び出すことなどはできない。

js
class Hoge {
  constructor() {
    const a = 'AAA';
    console.log(a); 
  }
}

const hoge = new Hoge();
console.log(hoge.a) // undefined

this.a(≠ const a)を呼び出しているためundefinedとなる

js
class Hoge {
  constructor() {
    const a = 'AAA';
    console.log(a); 
  }

  run() {
    console.log(this.a);
  }
}

const hoge = new Hoge();
hoge.run(); // undefined

定数a (const a) とプロパティa (this.a) は異なる。
さらにプロパティthis.aは未定義なのでundefinedとなる。

js
class Hoge {
  constructor() {
    const a = 'AAA';
    console.log(a); 
  }

  run() {
    console.log(a);
  }
}

const hoge = new Hoge();
hoge.run(); // エラー

コンストラクタ内の定数aではなく、グローバル変数aを呼び出すが未定義なのでエラー。

関数の定義・実行

js
class Hoge {
  constructor() {
    function b() {
      console.log('BBB')
    }

    const c = () => {
      console.log('CCC');
    };

    b();
    c();
  }
}

const hoge = new Hoge();
// BBB
// CCC

この場合コンストラクタ内で定義した関数は、コンストラクタ内でしか実行できない。

ただし次のようにプロパティに関数を格納すればコンストラクタ内に加え、メソッドのように実行したり、他のメソッドから呼び出すことができる。

js
class Hoge {
  constructor() {
    this.b = function() {
      console.log('BBB')
    }

    this.c = () => {
      console.log('CCC');
    }

    this.b();
    this.c();
  }

  run() {
    this.b();
  }
}

const hoge = new Hoge();
// BBB
// CCC

hoge.b(); // BBB
hoge.c(); // CCC
hoge.run(); // BBB
0
0
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
0
0