3

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

3
  • possible duplicate of What's wrong with my event handler? Commented Dec 13, 2012 at 5:49
  • 1
    FYI, $("#button1").click(cat.getCol()); executes cat.getCol immediately, not on button click. Commented Dec 13, 2012 at 5:50
  • Thanks. it should be something about that 'this' things. Commented Dec 13, 2012 at 6:00

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

Generally in JS, this refers to the owner of the function .. So, in both cases when that function is called, this would resolve to the (jQuery object of the)element that has been clicked. In the first case, this is not 'cat', so col is not defined. Thus, it gives undefined. In the second case, no this, so cat.col resolves to Red.

I think you need to do some reading about JS functions, this, anonymous functions .. http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/ is a good place to start.

This on MDN - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.