4 ms·
The syntax is definitely awkward. But efforts like coffee-script http://jashkenas.github.com/coffee-script/ http://jashkenas.github.com/coffee-script/ are here
by Detrus 16y ago
The syntax is definitely awkward. But efforts like coffee-script http://jashkenas.github.com/coffee-script/ http://jashkenas.github.com/coffee-script/ are here to alleviate some of these pain points.
- amadiver 16y agoUnfortunately, CoffeeScript doesn't support implicit "this". I'm working on that problem, and I hope to share it soon.
- jashkenas 16y agoThe main problem with JS "this" is that in a language where everything else is lexically scoped, "this" is dynamically scoped -- taking the value of whatever object the function happens to be attached to at call time. To use a Ruby metaphor, imagine if "instance_eval" were the default way to call a method. One of the main features that CoffeeScript adds to help with "this" issue is the bound function literal (the fat arrow). A regular function looks like this: add = (num) -> this.value += num And compiles into the regular JavaScript you'd expect: var add; add = function(num) { return this.value += num; }; However, if you define the function with a fat arrow instead: add = (num) => this.value += num You'll get a function bound to the current value of "this", and when you pass the function off to another object as a callback -- a DOM event handler, or success callback from an Ajax request -- the value of "this" doesn't change. Here's perhaps a better example, from jQuery: var self = this; $(".row").bind("click", function() { this.setText("Clicked!"); }); And in CoffeeScript, without the "self = this" bit: $(".row").bind "click", => this.setText "Clicked!"