closures and variables
来源:互联网 发布:没卡怎么在淘宝买东西 编辑:程序博客网 时间:2024/06/06 12:43
There is one notable side effect of this scope-chain configuration. The closure always gets the last value of any variable from the containing function.Remember that the closure stores a reference to the entire variable object, not just to a particular variable.This issue is illustrated clearly in the following example:
function createFunctions() {let reslt=[];for(let i=0;i<10;i++){reslt[i]=function () {return i;}}return reslt;}
This function returns an array of functions. Since each function has the createFunctions() activation object in its scope chain, they are all referring to the same variable, i .
You can, however, force the closures to act appropriately by creating another anonymous function, as follows:
function createFunctions() {let reslt=[];for(let i=0;i<10;i++){reslt[i]=function(num){return function () {return num;}}(i);}return reslt;}
With this version of createFunctions(), each function returns a different number. Instead of assigning a closure directly into the array, an anonymous function is defined an called immediately. The anonymous function has one argument,num, which is the number that the result function should return. The variable i is passed in as an argument to the anonymous function. Since function arguments are passed by value, the current value of i is copied into the argument num. Inside the anonymous function, a closure that accesses num is created returned. Now each function in the result array has its own copy of num and thus can return separate numbers.
阅读全文
0 0
- closures and variables
- Scope And Closures
- JavaScript: Closures and Modules
- Iteration and closures in R
- JavaScript quirk 7: inadvertent sharing of variables via closures
- closures
- Closures
- closures
- 8.3 Variables and parameters
- Incrementing and Decrementing Variables
- Using Data and Variables
- mutex and Condition Variables
- Global and Local Variables
- Blocks and Variables
- Blocks and Variables
- static variables and functions
- Global and Local Variables
- Local variables and pointer
- 1059. C语言竞赛(20)
- svm参数
- 51获取MPU6050数据并通过匿名上位机显示波形
- vsnprintf用法解析
- 数据结构C语言版赫夫曼树
- closures and variables
- 拓扑排序
- 关于TP框架隐藏index.php
- CentOS7 yum安装mongodb
- 在Kali linux下安装XAMPP并搭建DVWA遇到的问题及解决办法
- itop4412 uboot 学习详细记录(二丶Exynos4412 uboot的组成)
- Codeforces Round #449 (Div. 2) D(思维)
- 【安全牛学习笔记】OWASP_ZAP
- springmvc下的Token设计