22 Mar 2012

Classes: introduction

First of all, I want to say several words about classes in CoffeeScript. In fact, any class here is just a map, where keys are field names and values are anything you want - numbers, strings, functions... Here is very simple example:
class Animal
  name: undefined
  @numberOfRegisteredAnimals: 0
  
  constructor: (@name) ->
    Animal.numberOfRegisteredAnimals += 1

  @printNumberOfRegistedAnimals: () ->
    console.log "The number of registered animals is equal to", 
            Animal.numberOfRegisteredAnimals 
  
  sayName: () ->
    console.log "My name is " + @name + ", " + @voice() 

class Cat extends Animal
  voice: () ->
    return "meow!!!"

class Dog extends Animal
  voice: () ->
    return "woof!!!"

Animal.printNumberOfRegistedAnimals()
cat = new Cat "Kuzya"
cat.sayName()
Animal.printNumberOfRegistedAnimals()
dog = new Dog "Sharik"
dog.sayName()
Animal.printNumberOfRegistedAnimals()
The output is:
The number of registered animals is equal to 0  
My name is Kuzya, meow!!!  
The number of registered animals is equal to 1  
My name is Sharik, woof!!!  
The number of registered animals is equal to 2  
It's very simple, isn't it? This example demonstrates most of the constructions that you may need when using classes in CoffeeScript: constructors, normal properties and methods, static property (line 3) and static method (lines 8-10), inheritance (note words 'extends Animal' in lines 15 and 19. Some remarks:
  • @ is the same as 'this.' but shorter and thus is used more often.
  • When you want to determine something static, you start it's name from @, because it's a property of class prototype (I will tell a bit more about prototypes later). When you want to use this property or method, you start from class name.
  • Line 2 is absolutely unnecessary. This field will be included in prototype as soon as you use it somewhere (e.g. in line 5). But I do prefer to write this line. It makes code a bit more clear for me.

To be continued...

No comments:

Post a Comment