CoffeeScript is a popular, elegant, and user-friendly programming language that compiles into JavaScript. One of its key features is the ability to work with classes and object-oriented programming (OOP) concepts seamlessly. In this article, we’ll explore how to declare and use classes in CoffeeScript, providing real-world examples to illustrate the process.
Understanding CoffeeScript Classes
CoffeeScript’s class syntax simplifies the creation and management of objects and encapsulation of data and methods. It closely resembles class declarations in other programming languages like Python or Ruby, making it easier for developers to work with OOP principles.
Declaring a CoffeeScript Class
To declare a class in CoffeeScript, use the class
keyword followed by the class name. Here’s a basic example:
class Animal
constructor: (name) ->
@name = name
speak: () ->
console.log "#{@name} says something."
In this example, we define an Animal
class with a constructor that takes a name
parameter and a speak
method for logging the animal’s speech.
Creating Instances of a Class
Once you’ve defined a class, you can create instances of it using the new
keyword:
cat = new Animal("Whiskers")
dog = new Animal("Buddy")
cat.speak() # Outputs: Whiskers says something.
dog.speak() # Outputs: Buddy says something.
Here, we create two instances of the Animal
class, cat
and dog
, and call the speak
method on each of them.
Inheritance and Extending Classes
CoffeeScript supports inheritance through the use of the extends
keyword. You can create a subclass that inherits properties and methods from a parent class. Here’s an example:
class Bird extends Animal
fly: () ->
console.log "#{@name} can fly."
parrot = new Bird("Polly")
parrot.speak() # Outputs: Polly says something.
parrot.fly() # Outputs: Polly can fly.
In this case, the Bird
class extends the Animal
class, inheriting the speak
method and adding its own fly
method.