Home > Web Front-end > JS Tutorial > body text

Popular understanding of closures - 5Clay

一个新手
Release: 2017-10-09 09:54:50
Original
1563 people have browsed it

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()) //输出我是通过闭包改变的值
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template