如何定义多个CoffeeScript类的属性
我想在创建新对象时定义不同“类”/“原型”的多个属性如何定义多个CoffeeScript类的属性,coffeescript,prototypal-inheritance,Coffeescript,Prototypal Inheritance,我想在创建新对象时定义不同“类”/“原型”的多个属性 class Animal constructor: (@name, @temperament, @diet) -> #methods that use those properties eat: (food) -> console.log "#{name} eats the #{food}." class Bird extends Animal constructor: (@wi
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=newcat(tailLength:“long”,name:“Mr.Whiskers”,气质:“Lazy”)
,这样我就可以定义不符合顺序的属性,如果我没有定义像“diet”这样的属性,它将返回默认值
我的理解是原型方法会冒泡,所以如果我调用
myCat.eat“猫粮”
,输出应该是“胡须先生吃猫粮。”
但是。。。这不可能,因为Animal类没有得到新猫的名字。如果你指的是“对象”,就使用{}
他的问题毫无意义,但这个答案太酷了。@michelpm是的,对不起。当你不理解概念时,很多时候是因为缺乏合适的词汇来描述它们。只是一般的误解。没关系,我已经习惯了——很高兴我帮了忙。@user1737909谢谢!100%我想做的事。:)@我错了,你的问题很好。我太专注于代码了。
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")