Alexis
Alexis

Reputation: 25163

Getting to class variable from instance of Class in CoffeeScript

I have a class like this:

class Cow
  @feet : 4

  constructor: (@name) ->

bes = new Cow "Bessie"

The question is, is it possible to access feet only given bes?

Upvotes: 15

Views: 5035

Answers (1)

mu is too short
mu is too short

Reputation: 434665

You can use the JavaScript constructor property to get at the class and there you will find your feet:

class Cow
    @feet: 4
    constructor: (@name) ->

class HexaCow extends Cow
    @feet: 6

bes = new Cow('Bessie')
pan = new HexaCow('Pancakes')

alert(bes.constructor.feet) # 4
alert(pan.constructor.feet) # 6
​

Demo: http://jsfiddle.net/ambiguous/ZfsqP/

I don't know of any special CoffeeScript replacement for constructor though.

Upvotes: 26

Related Questions