Re:Why I still prefer Prototype to jQuery
by fh on Monday January 12, 2009 @05:37PM
(#431257)
Not having extensively used either jQuery or Prototype, I found this comparison interesting. But the entire discussion about jQuery "stealing" `this` is somewhat misinformed. Javascript closures don't caputure the value of `this`; instead, the value of `this` is determined at the call site. If the function is called as a method (using the `object.method()` syntax), `this` is bound to `object`; otherwise, `this` is bound to the global object (called `window` in browsers). The behavior I just described makes `this` is almost useless in Javascript closures, and the "idiomatic Prototype" example the author gives cannot possibly work:
If you want to do that, you have explicitly bind `this` to a (differently named) variable in the outer scope:
[ Parent
| on HN ]
I will say this, use of this is very scary and requires me to look at the docs more often (need to know where in the scope chain this is being set).
In fact, I'd argue that in general seeing uses of this outside of object oriented code make me sit up and look very carefully, because its really easy to get spooky "action at a distance" type behaviour.
Re:Why I still prefer Prototype to jQuery
by richcollins on Monday January 12, 2009 @05:48PM
(#431273)
Or pass in an object to the function that will be bound to this.
$A(self.columns).each(function(item) { this.buildHeader(item); }, this);
In general I prefer the technique you described as it is the most frequent use case and simplifies the implementation of the function that executes the callback.
Re:Why I still prefer Prototype to jQuery
by dantheman on Monday January 12, 2009 @06:03PM
(#431286)
or you can use javascript call or apply
method.call (<object you want to be *this*>, params);>> "The behavior I just described makes `this` is almost useless in Javascript closures"
Hmm??
e.onmouseover = function(c) {return function() { c.dosomething()}}(this);
Then in the dosomething function, "this" references what you expect...
I don't see why you need a library to construct a simple closure.
Note how you haven't used the keyword `this` inside the closure. What you've written is functionally equivalent to the technique I described, assigning the `this` object to a temporary variable. The only difference is that you bind it with a lambda instead of a `var`.