1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JS(ES6) constructorの使い方

1
Last updated at Posted at 2018-12-16

class内で使われるconstrucorの使い方

JavaScriptのクラスについて整理するためにまとめました。

クラスとインスタンスの関係

クラス(設計図)を元に、インスタンス(もの)を生成する

コンストラクタとは

クラスにはコンストラクタと呼ばれる機能が用意されている。コンストラクタはインスタンスを生成するときに実行したい処理や設定を追加するための機能。

①コンストラクタの中に処理を書くバージョン

class Students{
  constructor(){
    console.log("学生です");    // インスタンスが生成された直後に実行される
  }
}

const student = new Students();    // クラスから新しいインスタンスを生成する

実行結果
学生です

②コンストラクタの中で、生成したインスタンスに関する情報を追加する。

コンストラクタの中で「this.プロパティ = 値」とすることで、生成されたインスタンスにプロパティと値を追加することができる。

class Students{
  constructor(){
    this.name = "田中";    // インスタンスのプロパティの値を指定
  }
}

const student = new Students();
console.log(student.name);

実行結果
田中

でもこのままでは、同じStudentクラスから生成されたnameプロパティの値がすべて'田中'になってしまいます。
Studentクラスから生成されたインスタンス(達)のnameプロパティ毎に、それぞれ異なった値を持たせたい。

③インスタンス毎に異なったプロパティの値を与えたい

class Students{
  constructor(name,age){      // 引数を設定
    this.name = name;         // インスタンスのnameプロパティの値を引数から受け取って設定
    this.number = number;     // インスタンスのnumberプロパティの値を引数から受け取って設定
  }
}

const student_1 = new Students('阿部', 18);    //コンストラクタの引数に値を渡す
const student_2 = new Students('伊藤', 17);

console.log(student_1.name);
console.log(student_1.age);
console.log(student_2.name);
console.log(student_2.age);

実行結果

阿部 18 伊藤 17

1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?