Home >Web Front-end >JS Tutorial >A simple understanding of JavaScript closures

A simple understanding of JavaScript closures

高洛峰
高洛峰Original
2016-10-15 16:09:431290browse

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

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

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

Statement:
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