モダンな JavaScript

今まで JavaScript は手続き型っぽく「なんとなく」使っていたのだが、最近ではクラスが使えるようになったりとキャッチアップの必要がありそう。

まずは、クラス(class)を使ってみる。

クラス class

そうはいっても、初心者向け記事のようなやつはダルくて実用的ではないので、「あるクラス内に別のクラスを含んでいる場合」というやつを試す。

まず、html ファイルの準備。

<!DOCTYPE html>
<html lang="ja">
<head>
 <title>TODO supply a title</title>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <script src="./js/test.js"></script>
</head>
<body>
 <div>JS test</div>
</body>
</html>

test.js はこういうものにした。

test.js
class a{
 constructor(){
  console.log('instance of a');
  class b{
   constructor(){
    console.log('instance of b');
   }
  }
 new b;
 }
}
new a;

class a1{
 constructor(){
  console.log('instance of a1');
  new b1;
 }
}
class b1{
 constructor(){
  console.log('instance of b1');
 }
}
new a1;

適当なウェブサーバーに設置。
html を出力させると、コンソール表示は

instance of a
instance of b
instance of a1
instance of b1

となる。

ただ、これは、テスト的コード。

あるクラス(a)に別のクラス(b)を含めて使いたい場合、b は必ずしもあるとは限らない。

new b というのはダサい。セッター&ゲッターを使いたいところ。

・・

・・・・

・・・・・・

などと言っていたのだが、上のような例(nested class などという)は JavaScript 非対応らしい。

ちゃんちゃん。

 

 

クリックclose

“モダンな JavaScript” への3件の返信

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です