Not true. JavaScript's `this` binding is absolutely not the only way to do it.
In Ruby:
class Foo
def hello
return proc { self }
end
end
puts Foo.new.hello.call #=> #<Foo:0x10e56c840>
In Python: class Foo(object):
def hello(self):
def zoo():
return self
return zoo
zoo = Foo().hello()
print(zoo()) #=> <__main__.Foo object at 0x102453f90>
In Ruby, blocks carry the original `self` as part of their variable scope. Rubinius exposes this if you want to poke around: ruby-1.9.3-head :007 > x = proc {}
=> #<Proc:0x1598@(irb):7>
ruby-1.9.3-head :008 > x.block.scope.self
=> main
In Python, it's a side-effect of the fact that you need to explicitly define `self` as a parameter.In Ruby, it's possible to override the `self` in a block using instance_eval, just as it's possible to explicitly define a `this` in JavaScript using `.call`.
The difference is that in JavaScript, the callee is always responsible for deciding what the `this` should be (often implicitly), where in Ruby and Python, the function's original binding includes its `self`.
edit: another way to put it would be that Coffee's fat arrow fix is the default in Ruby and Python.
(I didn't know about assigning self in instance_eval, though - that makes me all kinds of happy!)
What I meant to convey is that every language that uses first class functions (I guess I should say "any language with first class functions and the concept of this/self") has to deal with the problem of execution context. Languages like Ruby and Python assume the common case and bundle the context by default. Languages like Javascript and Lua don't, leaving it up to the caller to explicitly specify. In all cases, though, the callee has to be made aware of some context, which is what I meant by the `this` problem. My point is that since Javascript requires explicit binding, a language construct that allows Ruby-style implicit binding is nice syntactic sugar. The author seemed to be conveying the idea that using jQuery's $.proxy magically freed him from the need to pass context around, which is just simply not the case.
function Foo:Bar(baz) is the same as Foo.Bar = function(self, baz); invoking Foo:Bar("rebar") is sugar for Foo.Bar(Foo, "rebar"). self is never bound - it's just passed in (explicitly, via . syntax, or implicitly, vs : syntax). In all cases, the caller is always specified.
You can pass Foo.Bar around (as it's a function reference), but if you have something like:
Foo = {}
function Foo:Bar(baz)
print(baz)
end
local baz = Foo.Bar
Then baz has no binding information to Foo; defining the function with the : syntax is just syntactic sugar. To invoke, you would have to call: baz(Foo, "woohoo")
Just calling baz("woohoo")
populates self with "woohoo", and the bar parameter would be nil, demonstrating that there is no contextual binding to the function itself. foo = { x = 3 }
function foo:bar(baz)
return function(thud)
return thud + baz + self.x
end
end
womble = foo:bar(4)
womble(7) --> 14
Python I believe also closes over self as a variable, and Ruby has similar behavior for local procs, even though « self » is a special form in Ruby.This is in distinct contrast to JavaScript, where the value of the special form « this » goes nuts inside closures because it's attached to the function:
foo = { x: 3 };
foo.bar = function(baz) {
return function(thud) {
return thud + baz + this.x;
};
};
womble = foo.bar(4);
womble(7) # --> NaN
So in what way are you placing Lua and JavaScript together, and Python and Ruby together?[slightly rearranged for clarity]
Mentally, I was separating Javascript and Lua from Ruby because while the caller is explicitly passed in Javascript and Lua (either via call/apply, or as a parameter), Ruby methods are implicitly aware of their scope (and can't really be referentially passed around like Javascript or Lua methods). Lua "methods" aren't aware of their scope (though closures are.
So we have that Python's dot always binds, Ruby's dot always calls, and Lua's dot is always a table lookup, with Lua's colon being a separate syntax for (always) the compound operation with injected self-argument.
And then JavaScript is the schizophrenic one: « obj.foo(bar) » is not the same as « var y = obj.foo; y(bar) ». Property lookup and function call insert a hidden step between them when and only when directly composed, and a function call without an immediately adjacent property lookup in a way injects the opposite step of making « this » in the callee be the global object (I think). “Politicians lie in cast iron sinks.”
JavaScript is forced to make the pessimal choice of only ever having dynamic-bound "this", because of that favorite whipping boy ... prototypal inheritance.
If JavaScript had a notion of a class (even as a constructor function + prototype) definition, then it would be possible to tag methods with the correct instance reference, as in Ruby and in Python. Unfortunately, because the standard pattern for defining an instance method is:
Klass.prototype.method = function() {
...
};
... where the function is an expression just like any other, you have to have dynamic-bound this to make prototypes work correctly by default. function woot:donk() ... end
woot:donk()
is equivalent to woot.donk = function(self) ... end
woot.donk(woot)
and when you define a function normally e.g. function() ... end
there is no self parameter, thus the one from the parent scope is captured. The flaw with JS, really, is that it forces every function to be a method, and doesn't let you express whether you are defining one or the other.(think I got this right, my Lua is a bit rusty)
Klass.method := lambda { p self }
Also, if JavaScript looked like this, you wouldn't need the fat arrow: // Let's call this a "prototype function"
Klass.prototype.function method() {
…
}
Together with these rules:* A function always captures its outer `this`
* The getter of a prototype function (`thing.method`) always returns a binded function (where `this` == `thing`).
I don't think that's true: functions accessed via objects could very well be bound to the object (that's what Python does, accessing a method via an object instance returns a "bound method" which is curried with the instance, whereas accessing the same method via the class returns an "unbound method" which requires a class instance as its first argument).
Klass.prototype.method = options.method;Not really, it's trivial to create a dict-like object which allows access to keys as properties, just override `__getattr__`.
> In JavaScript an object is an object is an object
No, objects can have a non-null [[prototype]] indicating it was created from using `new` on a constructor.
> Klass.prototype.method = options.method;
Depends what `options` is.
I've seen some genuinely horrible Javascript. Like, stuff that so terribly abuses the language without any comprehension whatsoever of closures or context binding and only works because the author got stupidly lucky and/or abused globals so badly that the code was effectively one giant function. In both cases, bad developers writing bad code are going to produce unmaintainable messes. Doesn't mean that the language should be avoided. Garbage in, garbage out.
nasty: https://github.com/jashkenas/coffee-script/blob/master/src/r...
nasty: https://github.com/jashkenas/coffee-script/blob/master/src/o...
nasty: https://github.com/jashkenas/coffee-script/blob/master/src/c...
sexy: https://github.com/jashkenas/coffee-script/blob/master/src/g...
nasty: https://github.com/mirrors/gcc/blob/master/gcc/c-family/c-co...
nasty: https://github.com/mirrors/gcc/blob/master/gcc/c-family/c-le...
But you get the idea. I'm merely pointing out that compilers are tricky and complicated beasts. And especially in the rewriter CS has to jump through hoops to disambiguate.
Plus, if you don't like it at all, just don't use it and quit complaining. :)
You could say "don't take that job", but I think the point of the article is to make it clear that CoffeeScript is not an unvarnished win, and that choosing to use it will result in otherwise qualified people taking your advice and not wanting to work on your project.
getUser = (id) ->
url = "users/#{id}"
dfd = $.ajax
url: url
format: 'json'
method: 'get'
url: url
promise: dfd.promise()
was unreadable to me. $.ajax+'\n'+indent instantly triggers nesting, hence call, in my head. The way I instinctively parse this code makes the added parentheses just distractive noise to me. Actually I would have written it this way, which makes things tick even more: getUser = (id) ->
url = "users/#{id}"
dfd = $.ajax
url: url
format: 'json'
method: 'get'
url: url
promise: dfd.promise()
A single newline makes the whole thing absolutely obvious to me, including the possibly ambiguous meaning around the implicit return.> It's not a case against using Coffeescript - it's a case against writing terrible code.
Actually it looked like a case of change refusal and confirmation bias. The author seems to be well-versed in JavaScript, trying hard - consciously or not - to write JavaScript in CoffeeScript, which in turn produces terrible code. Every itch gets scratched, producing terrible irritation.
> you can’t compress [whitespace]
gzip. rake assets:precompile generates .gz for you so it doesn't even incur a performance hit on your servers.
> The increase in debugging complexity is a fair point, and it does add an extra step in between finding a problem and fixing it. However, in practice, I'm not sure I've ever had this be a major problem
Me neither. In fact the mapping is most of the times fairly obvious. Besides, editor enhancements[0], though not essential, helps a bit to not have to pull stuff in the browser every single time. Anyway SMAP support (or something close) is on the way[1] but in the meantime it doesn't bother me the least with CoffeeScript, thanks to it being so close to JavaScript.
[0] http://esa-matti.suuronen.org/blog/2011/11/28/how-to-write-c...
[1] http://www.infoq.com/news/2011/08/debug-languages-on-javascr...
Except when there's a regression in the compiler, and then it doesn't.
https://github.com/jashkenas/coffee-script/issues/1842
It's all good though, because "Pull requests are always welcome." :P
widget =
attach: ->
@el.bind 'click', @handler
handler: (event) =>
doStuffWithThis()
wrong.Handler is bound to whatever scope widget is in. http://jashkenas.github.com/coffee-script/#try:widget%20%3D%...
See how confusing fat arrow is?
Edit: Okay, I see what you're doing; attach is supposed to be invoked with a bound scope, which does change the binding. So yeah, my code won't work in your example. I'd argue that that's more of a lack-of-context problem in the example though, since it's dependent on knowledge of the usage of the attach() function to know that that binding behavior isn't desired. Given the context of the example, I contend my solution was acceptable. :)
Fat arrow there is still functionally equivalent to $.proxy.
To see what scope the fat arrow is bound to, all you need to do is scan up the parent scope in the file and look for a thin arrow (or a class declaration).
Your "whitespace problem" is my solution.
Mixins... Can you show me an example?
Times when you need a reference to a canonical function object, like with $.proxy and $.unbind. (CoffeeScript could implement => to set the original function as a property of the bound function)
Added a question on github: https://github.com/jashkenas/coffee-script/issues/1934
I'm writing a specific article on the issues with the fat-arrow, but the difference is nesting callbacks v. assigning.
I like the fat arrow in `class`.
The rest of the examples, though, don't hold much water. The takeaway from them is "it's possible to write terribly-factored code, even in a pretty language".
Can be rewritten as this, if it's more comfortable for you: !=, &&, ||, (), and the like are still usable in Coffeescript. If it makes the code easier to read, then use them!The whole concern with list comprehension syntax order is sort of a red herring - it works that way in Javascript 1.8, as well! In fact, nearly every language that implements list comprehension does it similarly. 160-column 1-liners are evil in any language, not just Coffeescript. If you don't like the "method, loop, condition" syntax of list comprehensions, that's a problem with list comprehensions, not with Coffeescript.
The points about the implicit returns and parentheses-less calls apply, as well. When it makes sense to explicitly use them for code clarity, use them.
For example, your confusing getUser method can be easily written as:
Voila, it's still coffeescript, and it's very readable, easy to understand, and not at all difficult to maintain.The fat arrow, like the rest of the examples, is yet-another-case of "Yes, you can shoot yourself in the face with it, if you abuse it". Event binding isn't the only case when you need to preserve scope! Sometimes (frequently, even) you need to pass around an anonymous function bound to a specific scope. The fat arrow is explicitly for that sort of work. If you abuse it every time you could otherwise just call call() or apply() (because you have access to the scope to invoke the function on, in addition to the function itself), then yeah, it's bad.
Have you even looked at the implementation of $.proxy() used in your examples there? Guess what it does? It creates a new anonymous function, binds it to the passed-in scope, and returns it. Which is exactly what the fat arrow does in Coffeescript. Why is it evil in Coffeescript, but okay in jQuery? Because you aren't aware it's happening?
Your "This is how you should do it" method in Coffeescript is wrong. It should be something like this:
That's clearer than any of your examples, Just Works, doesn't have a jQuery dependency, and is even less code than your corrected example. First-class functions have the `this` problem in every language, and the fat arrow is very nice syntactic sugar for what you have to do anyway.The purpose of Coffeescript is to make your life as a Javascript developer easier. If you're using it to make your life harder, you're doing it wrong. It's not a case against using Coffeescript - it's a case against writing terrible code.