Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript:Function in object is undefined when call by onclick

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...

like image 704
TKL Avatar asked Mar 22 '26 01:03

TKL


1 Answers

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

like image 128
Ray Toal Avatar answered Mar 24 '26 15:03

Ray Toal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!