简体   繁体   English

JavaScript对象的异常行为

[英]JavaScript object strange behaviour

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: HTML:

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

Function for DatePicker insertion: DatePicker插入功能:

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. “ mode”不是全局变量,在控制台中显示为“ undefined”。
When I call "insert_datepicker(2)" the onChange works fine, but shouldn't there be an error when the event is triggered? 当我调用“ insert_datepicker(2)”时,onChange可以正常工作,但是触发事件时是否应该没有错误?
How does the function "remembers" the note? 函数如何“记住”笔记?

It is because of closure nature of javascript , it allows an inner function to access the variables declared in the outer scope. 这是因为javascript关闭性质 ,它允许内部函数访问在外部范围中声明的变量。

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. 在您的情况下, mode变量在insert_datepicker函数内部声明,并且您有一个onChange的匿名内部函数,在此内部函数可以访问在insert_datepicker内部声明为封闭变量的变量。

mode is provided when you call insert_datepicker() . 调用insert_datepicker()时会提供mode mode in your case, when calling insert_datepicker(2) is actually 2 . mode你的情况,打电话时insert_datepicker(2)实际上是2 All datepickers attached this way will have their mode bound to the mode passed in when calling insert_datepickers . 以这种方式连接的所有datepicker将使其mode绑定到调用insert_datepickers时传递的mode

When you don't pass in mode , it will be undefined . 当您不通过mode ,它将是undefined Comparing it to 1 and 2 will yield false and will not execute the blocks of the statements. 将其与12进行比较将产生false并且将不执行语句的块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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