Reviewing these two code snippets, I am faced with a puzzle. The first code block fails to execute, while the second one successfully runs. This has left me perplexed, and I am seeking clarification from those who can shed some light on the matter.
[My current project involves developing a straightforward game using jQuery for compatibility with webkit browsers (and eventually for packaging with Titanium).]
Upon analyzing the first example, Firebug alerts me that "this.checkCloud" is not recognized as a function.
function Cloud(){
this.checkCloud = function(){
alert('test');
}
$("#"+this.cloudName).click(function(){
this.checkCloud();
});
}
Interestingly, the following implementation proves to be successful:
function Cloud(){
this.checkCloud = function(){
alert('test');
}
var _this = this;
$("#"+this.cloudName).click(function(){
_this.checkCloud();
});
}
The second version functions flawlessly.
What is the reason behind the failure of the first code? Could it be due to "this.checkCloud" being located within the anonymous function?