Detailed explanation of scope usage in js
This time I will bring you a detailed explanation of the use of js scope. What are the precautions when using js scope? The following is a practical case, let’s take a look.
JavaScript is used by many people now. Regarding the use of JavaScript, many people may not be very clear about scope and block-level scope. Here is an article to give you a detailed explanation. I think Let’s take a look together if you know more about it.
1. Description of block-level scope
Before learning JavaScript variable scope, we should clarify a few points:
a. JavaScript's variable scope is based on its unique scope chain.
b. JavaScript does not have block-level scope.
c. The variables declared in the function are defined throughout the function.
The variable scope of javascript is different from the C-like language commonly used, such as the code in C#:
static void Main(string[] args) { if(true) { int number=10; } Console.WriteLine(number); }
This code cannot be compiled because "number does not exist in the current context".
Because the scope of the variable here is limited by curly braces, it is called block-level scope.
In the block-level scope, all variables are within the curly braces of the definition. They can be used in the range from the beginning of the definition to the end of the curly braces. They are inaccessible outside this range, which means
if(true) { int number=10; Console.WriteLine(number); }
This is accessible because the variable is defined and used within the same curly braces.
But there is no concept of block-level scope in JavaScript.
2. Scope in javascript
1. Function limited variable scope
In JavaScript, variables defined in a function can be accessed inside the function, but cannot be accessed outside the function. Code:
<script type="text/javascript"> var num=function() { var number=10; }; try{ alert(number); }catch(e) { alert(e); } </script>
When the code is running, an exception will be thrown. The variable number is not defined. This is because variables defined in the function cannot be used outside the function. They can be used arbitrarily within the function, even before assignment:
<script type="text/javascript"> var num=function(){ alert(number); var number=10; alert(number); }; try{ num(); }catch(e){ alert(e); } </script>
After this code is run, no error will be thrown. It will pop up twice, namely undefined and 10
2. Subdomain accesses parent domain
A function can limit the scope of a variable, then the function in the function is a subdomain of the scope. The code in the subdomain can access the variables in the parent domain. The code is as follows:
<script type="text/javascript"> var func=function(){ var number=10; var sub_func=function(){ alert(num); }; sub_func(); }; func(); </script>
The result of executing this code is 10, but the code accessing the parent domain in the subdomain is also conditional
<script type="text/javascript"> var func=function(){ var number=10; var sub_func=function(){ var num=20; alert(num); }; sub_func(); }; func(); </script>
This code has one more "var num=20;" than the previous one. This code is in the subdomain, so the situation of the subdomain accessing the parent domain has changed. The result printed by this code is 20. At this time, the subdomain The num accessed is a variable in the child domain, not the parent domain. It can be seen that there are certain rules for access. When using variables in JavaScript, the JavaScript interpreter first searches whether there is a definition of the variable in the current scope. If there is, this variable is used. If not, it goes to the parent domain to find the variable. , and so on, until the top-level scope is still not found, an exception "Variable is not defined" will be thrown. The code is as follows:
<script type="text/javascript"> (function (){ var num=10; (function (){ var num=20; (function(){ alert(num); })(); })(); })(); </script>
After this code is executed, 20 will be printed. If "var num=20
" is removed, then 10 will be printed. Similarly, if "var num=10
" is removed, then it will be An undefined error occurred.
The following introduces JS scope and block-level scope
Scope is always the top priority in any programming language, because it controls the visibility and lifecycle of variables and parameters. Speaking of which, first understand two concepts: block-level scope and function scope.
What is block-level scope?
Any set of statements within a pair of curly braces ({ and }) belongs to a block, and all variables defined in it are invisible outside the code block. We call this block-level scope.
The function scope is easy to understand (*^^*). The parameters and variables defined in the function are not visible outside the function.
Most C-like languages have block-level scope, but JS does not. Please see the demo below:
//C语言 #include <stdio.h> void main() { int i=2; i--; if(i) { int j=3; } printf("%d/n",j); }
运行这段代码,会出现“use an undefined variable:j”的错误。可以看到,C语言拥有块级作用域,因为j是在if的语句块中定义的,因此,它在块外是无法访问的。
而JS是如何表现的呢,再看另一个demo:
functin test(){ for(var i=0;i<3;i++){ } alert(i); } test();
运行这段代码,弹出"3",可见,在块外,块中定义的变量i仍然是可以访问的。也就是说,JS并不支持块级作用域,它只支持函数作用域,而且在一个函数中的任何位置定义的变量在该函数中的任何地方都是可见的。
那么我们该如何使JS拥有块级作用域呢?是否还记得,在一个函数中定义的变量,当这个函数调用完后,变量会被销毁,我们是否可以用这个特性来模拟出JS的块级作用域呢?看下面这个DEMO:
function test(){ (function (){ for(var i=0;i<4;i++){ } })(); alert(i); } test();
这时候再次运行,会弹出"i"未定义的错误,哈哈,实现了吧~~~这里,我们把for语句块放到了一个闭包之中,然后调用这个函数,当函数调用完毕,变量i自动销毁,因此,我们在块外便无法访问了。
JS的闭包特性is the most important feature((*^^*) 大家懂的)。在JS中,为了防止命名冲突,我们应该尽量避免使用全局变量和全局函数。那么,该如何避免呢?不错,正如上文demo所示,我们可以把要定义的所有内容放入到一个
(function (){ //内容 })();
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of scope usage in js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

In Vue, there is a difference in scope when declaring variables between let and var: Scope: var has global scope and let has block-level scope. Block-level scope: var does not create a block-level scope, let creates a block-level scope. Redeclaration: var allows redeclaration of variables in the same scope, let does not.

BitgetLaunchpool is a dynamic platform designed for all cryptocurrency enthusiasts. BitgetLaunchpool stands out with its unique offering. Here, you can stake your tokens to unlock more rewards, including airdrops, high returns, and a generous prize pool exclusive to early participants. What is BitgetLaunchpool? BitgetLaunchpool is a cryptocurrency platform where tokens can be staked and earned with user-friendly terms and conditions. By investing BGB or other tokens in Launchpool, users have the opportunity to receive free airdrops, earnings and participate in generous bonus pools. The income from pledged assets is calculated within T+1 hours, and the rewards are based on
