enzoyaaaaa
enzoyaaaaa

Reputation: 60

Declare function as variable in Javascript (or Jquery)

$(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 ?

Upvotes: 1

Views: 111

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

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

Upvotes: 8

Related Questions