LoginSignup
0
0

More than 5 years have passed since last update.

なんだか間違っている気がするJavaScriptでスーパークラスからサブクラスの一覧を取得する方法

Posted at

まずはじめに何をやりたかったというと、スーパークラスのクラスメソッドからサブクラスの一覧を取得したかった(。
ES6になってクラスも定義できるし継承もできるのでRubyみたいにサブクラスの一覧がとれるとうれしいなと思った次第(確かできたよね?)。
でいろいろ調べてみた結果、自分の検索技術が未熟+英語とか十分に読めないこともあり、方法が見つからなかった。
しょうがないのでそれっぽいことをやろうと思って試行錯誤した結果以下のようになった。

class Animal {
  constructor(name){
    this.name = name;
    this.subArray = new Array();
    Animal.prototype.subArray.push(this);
  } 

  callName(){
    console.log(this.name);
  }
}

Animal.prototype.subArray = new Array();

class Dog extends Animal {
  callName(){
    console.log("犬 名前:" + this.name);
  }
}

class Cat extends Animal {
  callName(){
    console.log("猫 名前:" + this.name);
  }
}

var myDog = new Dog('ぽち');
var myCat = new Cat('たま');


console.log(Animal.prototype.subArray);

単純にAnimalのprototypeに配列作ってインスタンスが生成されるたびにプッシュしていくという代物。サブクラス一覧と言うよりは作られたインスタンス一覧だろうか。
多分もっといい方法があるんだろうけど、なんとなくやりたいことはできそうな気がする。
もっといい方法があったら教えて欲しい><

0
0
2

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