简体   繁体   English

回调函数的词法范围

[英]Lexical scope of callback function

could someone explain to me why startDate and endDate are not in scope in callback passed to filter function.有人可以向我解释为什么 startDate 和 endDate 在传递给过滤器函数的回调中不在范围内。

var events = [],
 eventsDataSource = [],
 statusChstatusChanges = [],
 statusChangesDataSource = [];

 function filterData() {
    var startDate = $('#start-date').data("kendoDatePicker").value();
    var endDate = $('#end-date').data("kendoDatePicker").value();

    events = eventsDataSource.filter(function (item) {
        debugger;
    });
    statusChanges = statusChangesDataSource.filter(function (item) {
        debugger;
    });
}

when I changed code to what's below it worked.当我将代码更改为下面的代码时,它起作用了。 starDate and endDate are in scope. starDate 和 endDate 在范围内。 Is lexical scope of callbacks/inline function created differently that function declarations?回调/内联函数的词法范围是否与函数声明不同?

function filterData() {
    var startDate = $('#start-date').data("kendoDatePicker").value();
    var endDate = $('#end-date').data("kendoDatePicker").value();

    function dateIsBetweenStartAndEnd(item) {            
        return new Date(item.Date) >= new Date(startDate) && new Date(item.Date) <= new Date(endDate);
    }

    events = eventsDataSource.filter(dateIsBetweenStartAndEnd);
    statusChanges =   statusChangesDataSource.filter(dateIsBetweenStartAndEnd);
}

I see you have some debugger statements in there.我看到你在那里有一些调试器语句。

Perhaps you are using Chrome's dev-tools and when you hit the debugger you are not able to access startDate and endDate .也许您正在使用 Chrome 的开发工具,当您点击调试器时,您无法访问startDateendDate

This is simply an optimization that the browser is doing because it's not seeing any access of those functions in your code.这只是浏览器正在进行的优化,因为它看不到您的代码中对这些函数的任何访问。

A quick way to verify this is to put a console statement above your debugger statement:验证这一点的一种快速方法是在debugger语句上方放置一个控制台语句:

console.log(startDate);
debugger; // now you will be able to access startDate

Your understanding of lexical scope is correct ...you are just hitting a runtime browser optimization.您对词法范围的理解是正确的……您只是在进行运行时浏览器优化。

For more information, see this chrome issue report .有关更多信息,请参阅此 chrome 问题报告

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

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