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
gives you
undefinedbecause the body ofcat.getColusesthiswhich ain’tcatwhen this thing runs. I would suggest usingFunction.prototype.bindhere, 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 thatthisstays bound to the enclosing object.Next
works fine because
getColusescatdirectly.Finally
is terribly wrong. The expression
cat.getCol()is a call which returnsundefined. 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