[jQuery] Binding "this" inside anonymous functions
Hey, jQuery community. I've used MooTools for about a year now, and
am experimenting with jQuery to see if I want to convert or not. So
far it's great, and I especially enjoy how easy it is to "find
things." Here's my first question, though, where MooTools offers a
solution that I haven't found in jQuery. Hopefully someone here can
help.
Let's say I have an anonymous function as a callback. In the case of
events, I know that the variable "this" will refer to the object which
is being altered. So, if I do something like the following, this will
refer to the link being iterated:
$('a').click(function() {
alert(this.href);
});
But if I have another anonymous function within this, I want to retain
the variable "this" to still refer to the "a" object. Here's an
example where the first "this" will work, but the second won't:
$('a').click(function() {
$.ajax({
url: this.href,
success: function(data) {
alert(this.href);
}
})
});
I understand why it won't work. MooTools offers a function called
"bind()" which I can use to attach any instance of "this" within this
anonymous function to another variable. So I could do something like
the following -- notice the bind(this):
$('a').click(function() {
$.ajax({
url: this.href,
success: function(data) {
alert(this.href);
}.bind(this);
})
});
Here's MooTools documentation on that function:
http://docs.mootools.net/Native/Function.js#Function.bind
I know I can use the following, and it will work, but is there
something similar in jQuery that's already available?
$('a').click(function() {
a = this;
$.ajax({
url: this.href,
success: function(data) {
alert(a.href);
}
})
});
Thanks in advance for your help.