0

Excuse me for a not-standart question, everything works fine, but it is still strange
On a webpage I use a datepicker from here
Here is the partial code:
HTML:

<div id="datepicker-calendar"></div>

Function for DatePicker insertion:

function insert_datepicker(mode)
{
    $('#datepicker-calendar').empty();  
    ...
    $('#datepicker-calendar').DatePicker({
        ...
        onChange    : function(date,el) {  
            if (mode == 1){
                doSmth1();
            }
            if (mode == 2){
                doSmth2();
            }
        }  
    });
    ...
}

'mode' is not a global variable and is shown as 'undefined' in console.
When I call "insert_datepicker(2)" the onChange works fine, but shouldn't there be an error when the event is triggered?
How does the function "remembers" the note?

Community
  • 1
  • 1
lvil
  • 4,326
  • 9
  • 48
  • 76

2 Answers2

1

It is because of closure nature of javascript, it allows an inner function to access the variables declared in the outer scope.

In your case the mode variable is declared inside insert_datepicker function and you have an anonymous inner function for onChange, here the inner function will have access to the variables declared inside insert_datepicker as closure variables.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

mode is provided when you call insert_datepicker(). mode in your case, when calling insert_datepicker(2) is actually 2. All datepickers attached this way will have their mode bound to the mode passed in when calling insert_datepickers.

When you don't pass in mode, it will be undefined. Comparing it to 1 and 2 will yield false and will not execute the blocks of the statements.

Joseph
  • 117,725
  • 30
  • 181
  • 234