2

我想在创建新对象时定义不同“类”/原型的多个属性。

class Animal
    constructor: (@name, @temperament, @diet) ->

    #methods that use those properties
    eat: (food) ->
        console.log "#{name} eats the #{food}."

class Bird extends Animal
    constructor: (@wingSpan) ->

    #methods relating only to birds

class Cat extends Animal
    constructor: (@tailLength) ->

    #methods relating only to cats

myCat = new Cat ("long", {"Mr. Whiskers", "Lazy", "Carnivore"})

不过,我做错了什么。只有 Cat 的构造函数似乎可以获得任何属性。

另外,有没有办法用键/值对来定义它们?理想情况下,我会写一些类似的东西myCat = new Cat (tailLength: "long", name: "Mr. Whiskers", temperament: "Lazy"),这样我就可以定义不按顺序排列的属性,如果我未能定义像“饮食”这样的属性,它会退回到默认值。

我的理解是原型方法会冒泡,所以如果我调用myCat.eat 'cat food',输出应该是"Mr. Whiskers eats the cat food."But... 它不可能,因为 Animal 类没有得到新 Cat 的名字。

4

1 回答 1

2

{}如果您的意思是“对象”,请使用。

class Animal
    constructor: ({@name, @temperament, @diet}) ->

    #methods that use those properties
    eat: (food) ->
        console.log "#{@name} eats the #{food}."

class Bird extends Animal
    constructor: ({@wingSpan}) ->
      super

    #methods relating only to birds

class Cat extends Animal
    constructor: ({@tailLength}) ->
      super

    #methods relating only to cats

myCat = new Cat(tailLength: "long", name: "Mr. Whiskers", temperament: "Lazy", diet: "Carnivore")
于 2013-06-10T00:16:24.257 回答