【问题标题】:How to define properties to multiple CoffeeScript classes如何为多个 CoffeeScript 类定义属性
【发布时间】:2013-06-10 08:16:24
【问题描述】:

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

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 类没有获得新的Cat 名称。

【问题讨论】:

    标签: coffeescript prototypal-inheritance


    【解决方案1】:

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

    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")
    

    【讨论】:

    • 他的问题几乎没有意义,但这个答案太酷了。
    • @michelpm 是的,对不起。当你不理解概念时,很多时候是因为缺乏合适的词汇来描述它们。只是一般的误解。
    • 没关系,我已经习惯了——很高兴能帮上忙。
    • @user1737909 谢谢! 100% 我想做的事。 :)
    • @aminimalanimal 我错了,你的问题很好。我过于关注代码了。
    猜你喜欢
    • 2011-01-07
    • 2012-01-10
    • 2021-05-27
    • 2017-01-17
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    相关资源
    最近更新 更多