jQuery generally abuses (or takes advantage of, depending on your perspective) the value of "this" in its callback functions, in places where it would really be better to have an explicit argument. For example:
AccountView.prototype.render = function() {
$(".account").click(function(e) {
// `this` is now the same as `e.currentTarget`
// But `e.target` is also useful.
// And you what you really want is for `this`
// to still point at the AccountView instance.
});
};
@jashkensas what you want though would break the way closures are handled in javascript. What you should do if you still want access to Accountview is to trap a variable with a reference to it in the closure. Using your jquery example:
AccountView.prototype.render = function() {
$(".account").click( { that: this }, function(e) {
// 'that' now holds a reference to AccountView
});
};
If you don't want to use (or you are using an older version of jquery without the eventData) you could use a closure:
$(".account").click( (function(that) {
return function(e) {
// 'that' now holds a reference to AccountView
})(this);
});
Yes, functions in JavaScript have dynamic "this" instead of lexical "this" -- that's part of the point we're discussing. It helps when defining ad-hoc prototypes, but hurts when writing callback functions (or any nested function, really) ... and is an active point of concern for the ES committee.
LoL I did not realize that. To me, I think I've just made my peace with the way it is. I don't think that jQuery needs to be changed in the way mentioned though - to me, 'this' is context sensitive and in this case, it would refer to the current object and not the container