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

A question about scope in JS

php中世界最好的语言
Release: 2018-03-12 17:38:56
Original
1433 people have browsed it

This time I bring you a question about the scope of JS. What are the precautions for JS about the scope? The following is a practical case, let's take a look.

var a = 1;function foo () {    console.log(a);    var a = 2;    console.log(a);
}
foo();
Copy after login

Please write the output values ​​of the first console.log and the second console.log respectively.


JavascriptFunction Initialization sequence of variables

Pre-execution period

1. The function declaration is initialized and placed To the global variable (global context) window

2. The variable declared by var is placed in the global variable (global context) window, or the context where var is located, such as inside the function, and the initial value is undefined

Execution period

When the code is executed, variable assignment will occur. Variables declared without var are only created after the code is executed, and then placed in the global variable (global context) window

Javascript Context

Global Context: Window

Function context: Variables declared using var inside a function are local variables and will be garbage collected after leaving the scope of the function. Closures are not garbage collected.

That is, the variables declared by var will be placed in the corresponding context during the pre-execution period, and then during the execution period, the variables in the corresponding context will be assigned values.

Answer

undefined 2

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website

Other related articles!

Recommended reading:

Angular’s ​​Beginner’s Tutorial

Node.js’s Beginner’s Tutorial (2)

Node.js tutorial for beginners (1)

The above is the detailed content of A question about scope in JS. 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