Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting to class variable from instance of Class in CoffeeScript

Tags:

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?

like image 787
Alexis Avatar asked Mar 01 '12 23:03

Alexis


People also ask

Can an instance method access a class variable?

Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.

Which is the syntax to access instance variable?

Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference. VariableName.

What is a Javascript instance variable?

An instance variable is just a property of an object, as Felix Kling said. You can't use props because that's referencing a global or local variable called props . What you want to access is the current value of props for the current component, stored in this.

Which method is used to initialize the instance variable of a class?

You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.


1 Answers

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.

like image 195
mu is too short Avatar answered Oct 19 '22 00:10

mu is too short