1
$(function(){
    //choose one below at once, the results are different 
    $('#click').click(clickMe.popup);   
    $('#click').click(clickMe.popup()); 
});

 var clickMe = {
     message: 'hello',
     popup: function(){
         alert(this.message);
     }
}

<input type='button' value='click me' id='click' />

the results are different,

  1. when I choose the first one, I get a popup when clicking the button, but it shows "undefined".

  2. when I choose the second one, I automatically get a popup when loading in, and there is the "hello" message.

Question :

  1. what's the different between popup() and popup ?
  2. what's wrong with the message inside the popup ?
1
  • One shows what popup is (function) other invokes it, which returns undefined. Commented May 25, 2015 at 13:38

1 Answer 1

8

what's the different between popup() and popup ?

popup() calls the function. popup just refers to it (e.g., so you can assign it as a click handler).

what's wrong with the message inside the popup ?

When you hook it up as

$('#click').click(clickMe.popup);

...the click will call the function, but with this referring to the DOM element, not your clickMe object. You can use Function#bind to fix that:

$('#click').click(clickMe.popup.bind(clickMe));

Function#bind returns a function that, when called, will call the original with the this value you provide. If you need to support old browsers (such as IE8) that don't have Function#bind, jQuery provides $.proxy that does much the same thing:

$('#click').click($.proxy(clickMe.popup, clickMe));

...or you can just shim/polyfill Function#bind (a search will give you several implementations).

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

2 Comments

another question, why the popup automatically triggered when I choose the second one ? it should only happen when I click the button.
@angelyaaaaa: Because as I said above, popup() calls the function. $('#click').click(clickMe.popup()); calls clickMe.popup() and passes its return value into click, exactly the way foo(bar()) calls bar and passes its return value into foo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.