JavaScript constructor()でクラスのオブジェクトを作成する
環境
Google Chrome 109.0.5414.120
Windows 10 Home 64bit
構文
1.クラスの宣言
class クラス名{
constructor(引数){処理コード}
}
2.インスタンス生成
インスタンス名 = new クラス名(値)
クラスを呼び出します。
使用例
class Test {
constructor(val) {
this.val = val * 3
}
}
const res = new Test(10)
console.log(res.val)
class Test {
constructor(val) {
this.val = val * 3
}
}
const res = new Test(10)
console.log(res.val)
class Test { constructor(val) { this.val = val * 3 } } const res = new Test(10) console.log(res.val)
結果
30