Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
At their heart, classes in CoffeeScript are just glorified objects that produce a lot of boilerplate JavaScript code to let them do the things they do. Because classes are just plain objects—granted, objects with a lot of window dressing—scope of variables, attributes, and functions behave the same as they do in regular objects.
Let’s investigate by taking our Employee class again. Employees in real life have names, so let’s make sure our Employee class can reflect it. When we create a new instance of the Employee class, we want to have the name passed in and assigned to an attribute that is scoped to the instance of the new Employee object.
Example: (source: class_scope.coffee)
class Employee
constructor: (name)->
@name = name
dob: (year = 1976, month = 7, day = 24)->
new Date(year, month, day)
emp1 = new Employee("Mark")
console.log emp1.name
console.log emp1.dob()
emp2 = new Employee("Rachel")
console.log emp2.name
console.log emp2.dob(1979, 3, 28)