JavaScript Class Patterns – In CoffeeScript
Posted
by Liam McLennan
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Liam McLennan
Published on Sat, 19 Mar 2011 06:47:58 GMT
Indexed on
2011/03/19
8:10 UTC
Read the original article
Hit count: 307
Recently I wrote about JavaScript class patterns, and in particular, my favourite class pattern that uses closure to provide encapsulation. A class to represent a person, with a name and an age, looks like this:
var Person = (function() { // private variables go here var name,age; function constructor(n, a) { name = n; age = a; } constructor.prototype = { toString: function() { return name + " is " + age + " years old."; } }; return constructor; })(); var john = new Person("John Galt", 50); console.log(john.toString());
Today I have been experimenting with coding for node.js in CoffeeScript. One of the first things I wanted to do was to try and implement my class pattern in CoffeeScript and then see how it compared to CoffeeScript’s built-in class keyword. The above Person class, implemented in CoffeeScript, looks like this:
# JavaScript style class using closure to provide private methods Person = (() -> [name,age] = [{},{}] constructor = (n, a) -> [name,age] = [n,a] null constructor.prototype = toString: () -> "name is #{name} age is #{age} years old" constructor )()
I am satisfied with how this came out, but there are a few nasty bits. To declare the two private variables in javascript is as simple as var name,age; but in CoffeeScript I have to assign a value, hence [name,age] = [{},{}]. The other major issue occurred because of CoffeeScript’s implicit function returns. The last statement in any function is returned, so I had to add null to the end of the constructor to get it to work.
The great thing about the technique just presented is that it provides encapsulation ie the name and age variables are not visible outside of the Person class. CoffeeScript classes do not provide encapsulation, but they do provide nicer syntax. The Person class using native CoffeeScript classes is:
# CoffeeScript style class using the class keyword class CoffeePerson constructor: (@name, @age) -> toString: () -> "name is #{@name} age is #{@age} years old" felix = new CoffeePerson "Felix Hoenikker", 63 console.log felix.toString()
So now I have a trade-off: nice syntax against encapsulation. I think I will experiment with both strategies in my project and see which works out better.
© Geeks with Blogs or respective owner