クラスの継承とコンストラクタ
ポイント
親クラスを継承した子クラスのコンストラクタでは、基本的にsuper()で親クラスのコンストラクタを呼び出す。
たとえば次のように親クラスParentを子クラスChildが継承した場合、子クラスに親クラスのプロパティが引き継がれている。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Parent   constructor: -> @name = "parent" class Child extends Parent ins = new Parent() console.log(ins.name) ins = new Child() console.log(ins.name) # 実行結果 # parent # parent | 
ところが次のように子クラスでコンストラクタを定義した場合は、親クラスのプロパティが引き継がれない。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Parent   constructor: -> @name = "parent" class Child extends Parent   constructor: -> ins = new Parent() console.log(ins.name) ins = new Child() console.log(ins.name) # 実行結果 # parent # undefined | 
これは子クラスのコンストラクタが親クラスのコンストラクタをオーバーライドしてしまったためで、この状態では親クラスのコンストラクタが実行されない。
そこで、子クラスのコンストラクタからsupper()で親クラスのコンストラクタを呼び出すと、親クラスのコンストラクタも実行され、プロパティが引き継がれる。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Parent   constructor: -> @name = "parent" class Child extends Parent   constructor: -> super() ins = new Parent() console.log(ins.name) ins = new Child() console.log(ins.name) # 実行結果 # parent # parent | 
コンストラクタが引数をとる場合も、super()で親クラスのコンストラクタに合わせた引数を指定すればよい。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Parent   constructor: (@name)-> class Child extends Parent   constructor: (name)-> super(name) ins = new Parent("parent") console.log(ins.name) ins = new Child("child") console.log(ins.name) # 実行結果 # parent # child | 
メソッドのオーバーライドと継承
例えば次のコードでは、親クラスのmethod()を子クラスのmethod()がオーバーライドしている。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Parent   method: -> console.log("in Parent") class Child extends Parent   method: -> console.log("in Child") ins = new Parent() ins.method() ins = new Child() ins.method() # 実行結果 # in Parent # in Child | 
子クラスからオーバーライドした親クラスのメソッドを呼び出したい場合は、super()を使う。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Parent   method: -> console.log("in Parent") class Child extends Parent   method: ->     super()     console.log("in Child") ins = new Child() ins.method() # 実行結果 # in Parent # in Child |