search
HomeWeb Front-endJS TutorialDetailed explanation of js scope and closure

Detailed explanation of js scope and closure

Nov 29, 2019 pm 02:02 PM
ScopeClosure

Detailed explanation of js scope and closure

Scope

There are two types of scope in JS: global scope|local scope

Lizi 1

console.log(name);      //undefined
var name = '波妞';
var like = '宗介'
console.log(name);      //波妞
function fun(){
    console.log(name);  //波妞
    console.log(eat)    //ReferenceError: eat is not defined
    (function(){
        console.log(like)   //宗介
        var eat = '肉'
    })()
}
fun();

[Related course recommendations: JavaScript Video Tutorial]

1. The name is defined globally and can be accessed globally, so (2) Printing can be printed correctly;

2. In function fun, if the name attribute is not defined, it will be found in its parent scope, so (3) can also be printed correctly.

3. The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions of the internal environment. Similar to One-way transparency, this is a scope chain, so (4) is not possible but (5) is.

Then the question arises, why the first print is "undefined" instead of "ReferenceError: name is not defined". The principle is simply the variable promotion of JS

Variable promotion: When JS parses the code, it will advance all declarations to the front of the scope


Chestnut 2

console.log(name);      //undefined
var name = '波妞';
console.log(name);      //波妞
function fun(){
    console.log(name)   //undefined
    console.log(like)   //undefined
    var name = '大西瓜';
    var like = '宗介'
}
fun();

is equivalent to

var name;
console.log(name);      //undefined
name = '波妞';
console.log(name);      //波妞
function fun(){
    var name;
    var like;
    console.log(name)   //undefined
    console.log(like)   //undefined
    name = '大西瓜';
    like = '宗介'
    console.log(name)   //大西瓜
    console.log(like)   //宗介
}
fun();

Note: is advanced to the current scope The front


Chestnut 3

printName();     //printName is not a function
var printName = function(){
    console.log('波妞')
}
printName();       //波妞

is equivalent to

var printName;
printName();     //printName is not a function
printName = function(){
    console.log('波妞')
}
printName();       //波妞

This way it is easy to understand, the function expression is in When declared, it is just a variable


Chestnut 4

{
    var name = '波妞';
}
console.log(name)   //波妞

(function(){
    var name = '波妞';
})()
console.log(name)   //ReferenceError: name is not defined

{
    let name = '波妞';
}
console.log(name)   //ReferenceError: name is not defined

As can be seen from the above chestnut, variables declared by var in JS cannot be hastily considered The scope of is the starting and ending scope of the curly braces. ES5 does not have a block-level scope, but is essentially a function scope. Only after the let and const definitions were introduced in ES6, there was a block-level scope.


Chestnut 5

function p1() { 
    console.log(1);
}
function p2() { 
    console.log(2);
}
(function () { 
    if (false) {
        function p1() {
            console.log(3);
        }
    }else{
        function p2(){
            console.log(4)
        }
    }
    p2();
    p1()
})();       
//4
//TypeError: print is not a function

This is a very classic chestnut. The declaration is made in advance, but because the judgment condition is no, the function body is not executed. So "TypeError: print is not a function" will appear. The same applies to while, switch, and for

closure

The function and the reference to its state, that is, the lexical environment (lexical environment) together form a closure. ). That is, closures allow you to access the outer function scope from the inner function. In JavaScript, functions generate closures every time they are created.

The above definition comes from MDN. Simply put, a closure refers to a function that has the right to access variables in the scope of another function.


● The key to closure is that its variable object should have been destroyed after the external function is called, but the existence of the closure allows us to still access the variable object of the external function. ,

//举个例子
function makeFunc() {
    var name = "波妞";
    function displayName() {
        console.log(name);
    }
    return displayName;
}

var myFunc = makeFunc();
myFunc();

Functions in JavaScript form closures. A closure is composed of a function and the lexical environment that creates the function. This environment contains all local variables that can be accessed when this closure is created

In the example, myFunc is a reference to the displayName function instance created when makeFunc is executed, and the displayName instance can still access its lexical Variables in the scope can access name. Thus, when myFunc is called, name can still be accessed, and its value 'Ponyo' is passed to console.log. The most common way to create a closure is to create another function inside a function


● Usually, the scope of a function and all its variables will end at the end of function execution was later destroyed. However, after creating a closure, the scope of the function will be saved until the closure no longer exists

//例二
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

//释放对闭包的引用
add5 = null;
add10 = null;

Essentially, makeAdder is a function factory - he creates the A function that adds the sum of a specified value and its arguments. In the example above, we used the function factory to create two new functions—one that sums its arguments plus 5 and another that sums 10 .

add5 and add10 are both closures. They share the same function definition, but store different lexical environments. In the context of add5, x is 5. And in add10, x is 10.

The scope chain of a closure includes its own scope, as well as the scope of the containing function and the global scope.


● Closure can only obtain the last value of any variable in the containing function

//栗子1
function arrFun1(){
    var arr = [];
    for(var i = 0 ; i < 10 ; i++){
        arr[i] = function(){
            return i
        }
    }
    return arr
}
console.log(arrFun1()[9]());     //10
console.log(arrFun1()[1]());     //10

//栗子2
function arrFun2(){
    var arr = [];
    for(var i = 0 ; i < 10 ; i++){
        arr[i] = function(num){
            return function(){
                return num
            };
        }(i)
    }
    return arr
}
console.log(arrFun2()[9]());     //9
console.log(arrFun2()[1]());     //1

In example 1, the arr array contains 10 Each anonymous function can access the external variable i. After arrFun1 is executed, its scope is destroyed, but its variables still exist in memory and can be accessed by anonymous functions in the loop. In this case, i is 10;

In Chestnut 2, there is an anonymous function in the arr array, and there are anonymous functions within the anonymous function. The num accessed by the innermost anonymous function is saved in the memory by the upper-level anonymous function, so it can be accessed. to the value of i each time.

This article comes from the js tutorial column, welcome to learn!

The above is the detailed content of Detailed explanation of js scope and closure. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)