javascript クラス(Class) 基本構文のサンプル

環境
Windows10 64bit 22H2
Google Chrome 122.0.6261.129(Official Build) (64 ビット)

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class MyClass {
// クラスメソッド
constructor() { ... }
method1() { ... }
method2() { ... }
method3() { ... }
...
}
class MyClass { // クラスメソッド constructor() { ... } method1() { ... } method2() { ... } method3() { ... } ... }
class MyClass {
// クラスメソッド
constructor() { ... }
method1() { ... }
method2() { ... }
method3() { ... }
...
}

new MyClass() で、リストされたすべてのメソッドをもつ新しいオブジェクトを作成します。
constructor() メソッドは new により自動で呼び出され、そこでオブジェクトを初期化できます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class User {
constructor(name) {
this.name = name;
}
sayHi() {
alert(this.name);
}
}
// 使い方:
let user = new User("yamada");
user.sayHi();
class User { constructor(name) { this.name = name; } sayHi() { alert(this.name); } } // 使い方: let user = new User("yamada"); user.sayHi();
class User {

  constructor(name) {
    this.name = name;
  }

  sayHi() {
    alert(this.name);
  }

}

// 使い方:
let user = new User("yamada");
user.sayHi();

説明
new User(“yamada") が呼び出されると:

新しいオブジェクトが作られます。
指定された引数で constructor が実行され、this.name へ代入します。

JavaScript

Posted by arkgame