Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript class and instance variables


May 09, 2021 CoffeeScript


Table of contents


Class and instance variables

Problem

You want to create class and instance variables (attributes).

Solution

Class variable

class Zoo
  @MAX_ANIMALS: 50
  MAX_ZOOKEEPERS: 3

  helpfulInfo: =>
    "Zoos may contain a maximum of #{@constructor.MAX_ANIMALS} animals and #{@MAX_ZOOKEEPERS} zoo keepers."

Zoo.MAX_ANIMALS
# => 50

Zoo.MAX_ZOOKEEPERS
# => undefined (it is a prototype member)

Zoo::MAX_ZOOKEEPERS
# => 3

zoo = new Zoo
zoo.MAX_ZOOKEEPERS
# => 3
zoo.helpfulInfo()
# => "Zoos may contain a maximum of 50 animals and 3 zoo keepers."

zoo.MAX_ZOOKEEPERS = "smelly"
zoo.MAX_ANIMALS = "seventeen"
zoo.helpfulInfo()
# => "Zoos may contain a maximum of 50 animals and smelly zoo keepers."

The instance variable

You must be in a class's method to define instance variables, such as properties, and initialize your default values in the constructor structure.

class Zoo
  constructor: ->
    @animals = [] # Here the instance variable is defined

  addAnimal: (name) ->
    @animals.push name

zoo = new Zoo()
zoo.addAnimal 'elephant'

otherZoo = new Zoo()
otherZoo.addAnimal 'lion'

zoo.animals
# => ['elephant']

otherZoo.animals
# => ['lion']

Warning!

Don't try to add variables outside the constructor (even as mentioned in elsewhere, this won't work as expected because of the potential JavaScript prototype concept).

class BadZoo
  animals: []           # Translates to BadZoo.prototype.animals = []; and is thus shared between instances

  addAnimal: (name) ->
    @animals.push name  # Works due to the prototype concept of Javascript

zoo = new BadZoo()
zoo.addAnimal 'elephant'

otherZoo = new BadZoo()
otherZoo.addAnimal 'lion'

zoo.animals
# => ['elephant','lion'] # Oops...

otherZoo.animals
# => ['elephant','lion'] # Oops...

BadZoo::animals
# => ['elephant','lion'] # The value is stored in the prototype

Discuss

Coffeescript saves the value of the class variable in the class instead of the prototype it defines. This is useful when defining variables in a class because they are not override by entity property variables.