An Example for Javascript Function Scoping and Closure
1. An Real World Example
In the patron detail page of the CRM system I'm working with, there’re large amount of data. To shorten user’s waiting time, we want to only load basic information at page loaded then dynamically load the others in ajax.
Now we’re going to call ajax in a “for” loop:
var subpanelIDs = ['panel1', 'panel2', 'panel3']; function loadSubpanels() { for (var i = 0; i < subpanelIDs.length; i++) { var panelID = subpanelIDs[i]; var successFunc = function (resultHtml) { console.log(panelID); //!!!It console 'panel3’ for 3 times //$('#'+panelID).html(resultHtml); }; $.ajax({ url: url, dataType: "html", success: successFunc }); } } loadSubpanels();
2. Function Scoping in Javascript
It’s about function scoping and closure.
Javascript is a lexical scoping language, also called static scoping, that means if a variable name's scope is a certain function, then its scope is the program text of the function definition: within that text, the variable name exists, and is bound to the variable's value, but outside that text, the variable name does not exist.
In our example, panelID’s scope is the text of whole function loadSubpanels. The 3 times of invoking “successFunc” are within a single invoking of “loadSubpanels”, so the current scope chain is shared by 3 “successFunc”. And result is that they all getting the same value of ‘panel3’.
Here we’re not going to explain detail for scoping and closure, you can refer to the book “javascript.the.definitive.guide”
3. Resolution
To avoid the 3 invoking of “successFunc” sharing same scope chain, we need to seperate them into another function “loadOnePanel”.
In this case each loadOnePanel will own a scope chain the the value of panelID will not change unexpectedly. The call back function now can fill 3 panels accrodingly.
var subpanelIDs = ['panel1', 'panel2', 'panel3']; function loadSubpanels() { for (var i = 0; i < subpanelIDs.length; i++) { loadOnePanel(subpanelIDs[i]); } } function loadOnePanel(panelID){ var successFunc = function (resultHtml) { console.log(panelID); }; $.ajax({ url: url, dataType: "html", success: successFunc }); } loadSubpanels();
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
· AI Agent爆火后,MCP协议为什么如此重要!