This article introduces to you a brief explanation of function scope and block-level scope in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Let’s look at a piece of code first
var a = true; function hoisting(){ if(!a){ var a = 2; } console.log(a) } hoisting(); // 最终结果:2
The logic of this code is
Will first look for variables in the current function domain
.
If it exists, declare the variable header first. If it does not exist, search
from the parent again until it is found.
Then we can rewrite it as
var a; // 变量声明 a = true; // 变量定义 function hoisting(){ var a; // 变量声明 if(!a){ a = 2; //变量定义 } console.log(a) // 先从自身函数域开始查找,找不到再去父作用域 } hoisting();
Javascript variables exist with functions as scope, and when they cannot be found locally, they will go to the parent level to find them.
may not have much to do with this article~~, the main thing is that closure constructs a new function domain.
Immediately Invoked Function Expression
His function is to assign a value to the variable before it is called
var a = (function(){ var a = 3 return a }())
The main function of let and const is to adjust the original function-level scope of JavaScript to the block-level scope
let a = 2; function block(){ if(!a){ let a =1 } console.log(a) } block() // 2
At this time, the scope of the function is divided Smaller, at the block level.
We can divide the code into three blocks
if block
block block
window block
Okay, now what will happen if we rewrite the function?
let a = 0; function block(){ if(!a){ let a =1 } console.log(a) } block() // 0
The final result is 0, when a cannot be found in the current block Sometimes it will go to the parent block to search, and the final value is 0
And the variables in the if block are only valid within the block
Recommended related articles:
JS object-oriented Encapsulated parsing in programming
How is jQuery’s self-calling anonymous function called?The above is the detailed content of A brief explanation of function scope and block-level scope in JavaScript. For more information, please follow other related articles on the PHP Chinese website!