5 ms·
Not having extensively used either jQuery or Prototype, I found this comparison interesting. But the entire discussion about jQuery "stealing" `this` is somewha
by fh 18y ago
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:
// Prototype
$A(this.columns).each(function(item) {
this.buildHeader(item);
});
If you want to do that, you have explicitly bind `this` to a (differently named) variable in the outer scope:
var self = this;
$A(self.columns).each(function(item) {
self.buildHeader(item);
});
- richcollins 18y agoOr 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.
- dantheman 18y agoor you can use javascript call or apply method.call (<object you want to be *this*>, params);
- litewulf 18y agoI 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.
- axod 18y ago>> "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.
- fh 18y agoNote 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`.
- axod 18y agoI don't use the keyword this inside the closure, but inside the function dosomething() I can happily use "this".