Adding Getters and Setters to a Ball of Yarn
30 Decenber 2013
That doesn't sound very useful. But you know what does? Adding getters and setters to a coffee-script class - after all, typescript has them, and I want to have similar functionality in my coffee-script.
Notice that I've augmented the Function object (:: is coffescript notation for prototype). This will add a get method to all functions, and in coffeescript a class is a function. We can define set the same way:
But what does that get us? Lets look at an implementation:
Inside of a class definition, but outside of a method scope, @ (this) refers to the class. So we are calling the get method of the class that we defined earlier, to define a getter on the class.
And, if we explicitly invoke the super object, we can inherit the new attributes:
Now aren't we glad we didn't turn into a big ball of yarn!