I am trying on some code here,
var cat={
col:"Red",
getCol:function(){
document.writeln(this.col);
}
}
function getCol(){
document.writeln(cat.col);
}
$(function(){
$("#button1").click(cat.getCol);
$("#button2").click(getCol);
})
But I got undefined for button1, "Red" for button2. Can someone tell me why?
And if I change it into $("#button1").click(cat.getCol());, I got the "Red" I need...
First of all
$("#button1").click(cat.getCol);
gives you undefined because the body of cat.getCol uses this which ain't cat when this thing runs. I would suggest using Function.prototype.bind here, or several of the other variants if you are worried about cross-browser compatibility. There are many published solutions to the problems of setting "methods" as event handlers and ensuring that this stays bound to the enclosing object.
Next
$("#button2").click(getCol);
works fine because getCol uses cat directly.
Finally
$("#button1").click(cat.getCol());
is terribly wrong. The expression cat.getCol() is a call which returns undefined. This is not a good value to set for a click handler. You just saw the document.write taking place, but not in response to a click.
ADDENDUM
Live demo using bind
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With