Reputation: 2131
Here are two samples of code. The first one does not work and the second one does, though I'm completely at a loss as to why. Can someone explain this?
[I'm writing a simple game using a bit of jQuery to be played in a webkit browser (packaged with Titanium later).]
In the first example, Firebug tells me that "this.checkCloud" is not a function.
function Cloud(){
this.checkCloud = function(){
alert('test');
}
$("#"+this.cloudName).click(function(){
this.checkCloud();
});
}
...but then this works:
function Cloud(){
this.checkCloud = function(){
alert('test');
}
var _this = this;
$("#"+this.cloudName).click(function(){
_this.checkCloud();
});
}
This one works perfect.
Why does the first one not work? Is it because "this.checkCloud" is inside of the anonymous function?
Upvotes: 0
Views: 199
Reputation: 95599
That is because the meaning of this
can potentially change each time you create a new scope via a function. The meaning of this
depends on how the function is invoked (and the rules can be insanely complicated). As you discovered, the easy solution is to create a second variable to which you save this
in the scope where this
has the expected/desired value, and then reuse the variable rather than this
to refer to the same object in new function scopes where this
could be different.
Upvotes: 2
Reputation: 26331
Try this:
function Cloud(){
this.checkCloud = function(){
alert('test');
}
var func = this.checkCloud;
$("#" + this.cloudName).click(function(){
func();
});
}
Upvotes: 1
Reputation: 43850
in this example:
$("#"+this.cloudName).click(function(){
this.checkCloud();
});
this
referrers to the element selected(jquery object).
what you can do is use private functions
var checkCloud = function(){
alert('test');
}
this way you can simply call it inside your anonymous function
$("#"+this.cloudName).click(function(){
checkCloud();
});
Upvotes: 2
Reputation: 42496
When you assign an even listener to an element, jQuery makes sure that this
will refer to the element. But when you create the _this
variable, you're creating a closure that jQuery couldn't mess with, even if it wanted to.
Upvotes: 0