我想在创建新对象时定义不同“类”/原型的多个属性。
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")
的内容,以便我可以定义不按顺序排列的属性,如果我未能定义像“diet”这样的属性,它将回退到默认值。
我的理解是原型方法会冒出来,所以如果我调用myCat.eat 'cat food'
,输出应该是"Mr. Whiskers eats the cat food."
但是......它不可能是因为Animal类没有得到新猫的名字。
答案 0 :(得分: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")