Speaking of closures, it involves the variable scope of the js function, which is divided into local variables and global variables. Variables outside the function can be directly read from inside the function, but variables inside the function cannot be directly read from outside the function.
But sometimes we need to get the local variables of the function, so the closure is generated. The closure is to define another function inside the function, as shown in the following code:
var foo=(function () { var a="11"; return{ get_a:function () { return a; }, new_a:function (newValue) { a=newValue; } } } ()) console.log(foo.a) //输出undefined,因为函数外部不能直接访问内部的局部变量 console.log(foo.get_a())//输出11 foo.new_a("我是通过闭包改变的值")//调用并且传参 console.log(foo.get_a()) //输出我是通过闭包改变的值
In this way we can The local variables inside a function are obtained outside it. In the above function, the function inside return is the closure.
The above is the detailed content of Popular understanding of closures - 5Clay. For more information, please follow other related articles on the PHP Chinese website!