What's the preferred method for accessing "this" in a javascript enclosure?
I often have code like this:
function Object() {
}
Object.prototype.getData() {
// THIS LINE:
var object = this;
$.ajax({
url: '...'
, success: function(data) {
object.onLoadData(data);
}
})
}
var o = new Object();
o.getData();
My question: what's the preferred paradigm for the "var object = this" bit above? I've seen this:
var self = thi开发者_开发问答s;
Which looks good, and I'll probably steal this method. What is the most common way of referring to parent object from within anonymous functions? Are there cleverer ways of doing this? I often find myself putting the "var object = this;" at the top of most object methods, and it seems like there might be some tricky way to avoid this.
Thanks!
Given your code, don't use a variable.
Use the context:
parameter to set the this
value in the callbacks.
Object.prototype.getData = function() {
$.ajax({
url: '...',
context: this, // <-----------set the context for the callbacks
success: function(data) {
this.onLoadData(data);
}
});
};
If the question wasn't meant to only deal with $.ajax
, then I'd use bind()
[docs] to bind the this
value to the function.
function successCallback(data) {
this.onLoadData(data);
}
Object.prototype.getData = function() {
$.ajax({
url: '...',
success: successCallback.bind( this );
});
};
If you need to support browsers that don't have .bind()
, then there's a shim in the docs link I provided that you can include.
Crockford seems to prefer var that=this
. If you are using the ExtJs library they seem to use
var me= this;
.
When it really comes down to it the name of the variable is not that important. Make sure you use something consistant with your peers and that makes sense to a novice programmer when they read it.
in my code, I use var that = this;
for this use case - I've also seen self
, although for me that gets a bit confusing, as in other languages it's a reserved keyword.
There's not any other way as far as I know to get around this, but as long as you pick a keyword only used for this case, and use it consistently throughout your codebase, it's a pretty clean way of dealing with it. I'd avoid var names like object
, as you'll more than likely use them elsewhere and create a confusing situation for yourself or someone maintaining your code.
Not really (that I'm aware of). I always use that
as the name, although it's more humorous than good practice.
精彩评论