简体   繁体   中英

Javascript Closure “creating Local variable for the callback function”

I am using javascript DatPicker like

datefield = $('fromdate');

datepicker = new DatePicker(wrapper, 
   {months:1
   , onSelect: function(datefield) {
                 return function() {
                   onDatePick();
                 } 
               }( datefield ) 
    });

where onSelect is a callback function which will be called when the user clicks on a Date. and DatePicker passed the Selected Date as Callback function's argument. This Date will be written in the datefield input field.

I thought that within the closoure this field will be avialble as local variable, but it is always undefined.

to add parameter to callback function, you need to do something like this:

datefield = $('fromdate');
datepicker = new DatePicker(wrapper, 
   {months:1
   , onSelect: (function(datefield) {
                 return function() {
                   onDatePick();
                 } 
               }) (datefield) 
    });

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