2016-12-22 9 views
-1

私はクラスHumanを持っており、クラスSocialBeingHumanから継承したいと思っています。しかし、super(Human)メソッドでは、Humanクラスは、最初の位置引数としてHumanクラスインスタンスに渡され、それはクイズとエラーです。継承する正しい方法は何ですかSocialBeingHumanからですか?coffescriptで引数付きのクラスを継承する方法は?

class Human # As biological creature 
    constructor: (@given_sex = null, 
        @age = null, # Age of the person 
        @max_age = 85) -> # Maximum allowed age of the person during person generation 

     _alive = true 

     alive: -> 
      @_alive 

     dead: -> 
      not @alive() 

     has_died: -> 
      @_alive = false 

     _available_sexes: {0: 'female', 1: 'male'} 

     sex: -> 
      _sex = @_available_sexes[@given_sex] 

     @generate_human() 

    generate_human: -> 
      @_alive = true 
      if @age is null 
       @age = Math.floor(Math.random() * @max_age) 
      if @given_sex is null 
       @given_sex = Math.floor(Math.random() * 2) 
      else if @given_sex not in [0,1] 
       n = @given_sex 
       err = 'Invalid sex value: ' + n 
       console.log(err) 
       throw new Error(err) 


class SocialBeing extends Human # Describes socialisation 
    constructor: (@first_name = null, 
        @second_name = null, 
        @middle_name = null, 
        @other_name = null) -> 
     super(Human) 

     marital_status: null 

h = new SocialBeing(first_name='Pal') # In JavaScript thows an error 

答えて

0

私はあなたが間違った方法でsuperを使用していると思います。 私はあなたの例

class Human 
    constructor: (@given_sex = null) -> 
      @generate_human() 

    generate_human: -> 
     if @given_sex is null 
      @given_sex = Math.floor(Math.random() * 2) 
     else if @given_sex not in [0,1] 
      n = @given_sex 
      err = 'Invalid sex value: ' + n 
      console.log(err) 
     else 
       console.log("my sex is", @given_sex) 

あなたの基底クラスは、これまでOKであるビットを凝縮しています。

class SocialBeing extends Human 
    constructor: (@first_name = null) -> 
      super 1 
      #or 
      super null 

superを呼び出すしかし、どういうわけか、これはあなたの基底クラスのコンストラクタの引数の目的に反しながら、今すぐあなたの派生クラスのために明示的のparamを設定することができます。通常の方法はまた、引数

class SocialBeing extends Human 
    constructor: (sex = null, @first_name = null) -> 
      super sex 

あなたの派生クラスのコンストラクタに、基本クラスのコンストラクタの引数を追加し、それに応じて

h = new SocialBeing(sex = 1, first_name='Pal') 

をあなたの派生クラスをinstatiateことであろうと、それにあったが、記述の定数がいいだろう同様

male = 0 
female = 1 
h = new SocialBeing(male, 'Pal') 

たり、特定のプログレッシブ;-)

を感じる場合はFBの58のジェンダー表現のいずれかを追加

今や明らかに、これらのctor引数をすべてsuperにパイプするのは面倒です。だから何をすることができるのですか?

class Human 
     constructor: (@given_sex = null, 
        @age = null, # Age of the person 
        @max_age = 85) 

class SocialBeing extends Human 
    constructor: (@first_name = null, 
        @second_name = null, 
        @middle_name = null, 
        @other_name = null) -> 
      super arguments... 

しかし、私はデザインの匂いと見なすことができます。

私はこれが役に立ちそうです。

関連する問題