Consider this HTML:
<p>Click me</p>
I would like to write an object with a click handler for each p
, but run into the problem that my click handler function could not be found.
This code does not work:
(function(){
var self = this;
$("p").each(function(){
$(this).click(self.myFunction);
});
self.myFunction = function(){ alert("myFunction"); }
})();
When I wrap the click handler assignment in a function it does work:
(function(){
var self = this;
$("p").each(function(){
$(this).click(function(){ self.myFunction(); });
});
self.myFunction = function(){ alert("myFunction"); }
})();
Question: Why doesn't $(this).click(self.myFunction)
work, but $(this).click(function(){ self.myFunction(); })
does?
Edit: The following code does work:
$("p").click(myFunction);
function myFunction(){ alert("myFunction"); }
Shouldn't this fail as well?
P.S. I got my object working without the need to wrap the function by moving the location of the function:
(function(){
var self = this;
self.myFunction = function(){ alert("myFunction"); }
$("p").each(function(){
$(this).click(self.myFunction);
});
})();
I guess the problem is parser related.