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

A simple understanding of JavaScript closures

高洛峰
Release: 2016-10-15 16:09:43
Original
1242 people have browsed it

Many books about JS such as "The Definitive Guide to JavaScript" or "Elevation" explain closures in such an obscure way that newbies can't understand it! But don’t be afraid, today I will explain to you what a closure is in a very simple way. This is an explanation of closures for novices. There are no obscure and blunt statements, and you can understand it at a glance. If there is anything wrong, please correct me!
To understand closures, you must first understand the scope of variables.
There are two variable scopes in JS: global variables and local variables. As the name suggests, global variables are variables that can be referenced at any location, and local variables are variables that can only be referenced at specific locations. See the code below.

var globalScope="global scope";
function f(){
    var localScope="local scope";
    console.log(globalScope);//global scope
}
console.log(localScope);//undefined
Copy after login

In function f(), you can access the globalScope defined outside the function body, but you cannot access the localScope defined outside the function body. This is the difference between global variables and local variables.
Could it be that localScope can never be accessed outside the function body? No, closure is born for this.

function f(){
    var localScope="local scope";
    return function(){
        console.log(localScope);
    }
}
f()();//local scope
Copy after login

We accessed the local variable localScope outside the function f(). The anonymous function defined within the function f() is a closure!

A simple understanding of JavaScript closures

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!