Google News
logo
CoffeeScript - Interview Questions
What are the Classes in CoffeeScript?
CoffeeScript 1 provided the class and extends keywords as syntactic sugar for working with prototypal functions. With ES2015, JavaScript has adopted those keywords; so CoffeeScript 2 compiles its class and extends keywords to ES2015 classes.
class Animal
  constructor: (@name) ->
​
  move: (meters) ->
    alert @name + " moved #{meters}m."
​
class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5
​
class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45
​
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
​
sam.move()
tom.move()
​
var Animal, Horse, Snake, sam, tom;
​
Animal = class Animal {
  constructor(name) {
    this.name = name;
  }
​
  move(meters) {
    return alert(this.name + ` moved ${meters}m.`);
  }
​
};
​
Snake = class Snake extends Animal {
  move() {
    alert("Slithering...");
    return super.move(5);
  }
​
};
​
Horse = class Horse extends Animal {
  move() {
    alert("Galloping...");
    return super.move(45);
  }
​
};
​
sam = new Snake("Sammy the Python");
​
tom = new Horse("Tommy the Palomino");
​
sam.move();
​
tom.move();​
​
Static methods can be defined using @ before the method name:
class Teenager
  @say: (speech) ->
    words = speech.split ' '
    fillers = ['uh', 'um', 'like', 'actually', 'so', 'maybe']
    output = []
    for word, index in words
      output.push word
      output.push fillers[Math.floor(Math.random() * fillers.length)] unless index is words.length - 1
    output.join ', '
​
var Teenager;
​
Teenager = class Teenager {
  static say(speech) {
    var fillers, i, index, len, output, word, words;
    words = speech.split(' ');
    fillers = ['uh', 'um', 'like', 'actually', 'so', 'maybe'];
    output = [];
    for (index = i = 0, len = words.length; i < len; index = ++i) {
      word = words[index];
      output.push(word);
      if (index !== words.length - 1) {
        output.push(fillers[Math.floor(Math.random() * fillers.length)]);
      }
    }
    return output.join(', ');
  }
​
};​
​
Finally, class definitions are blocks of executable code, which make for interesting metaprogramming possibilities. In the context of a class definition, this is the class object itself; therefore, you can assign static properties by using @property: value.
Advertisement