简体   繁体   中英

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 ?

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

popup() calls the function. popup just refers to it (eg, 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM