In this article, we will introduce you to the scope and block-level scope in Javascript. Scope is always the top priority in any programming language, because it controls the visibility and life cycle of variables and parameters. . Let me introduce to you the scope and block-level scope in Javascript. Friends who need it can refer to 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. For example, the code in C#:
static void Main(string[] args) { if(true) { int number=10; } Console.WriteLine(number); }
This code is Compilation fails 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 defined curly braces. They can be used in the range from the beginning of the definition to the end of the curly braces. They cannot be accessed outside this range, that is to say
if(true) { int number=10; Console.WriteLine(number); }
This can be accessed because the definition and use of the variable are 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, inside the function The defined variables 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 run, an exception will be thrown. The variable number is not defined because variables defined in a 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, and it will pop up twice, namely undefined and 10
2. The subdomain accesses the parent domain
Functions can limit variables scope, 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 accessing the code of 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 The code section 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 access The num 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 Print out 20. If you remove "var num=20
", then the printed value is 10. Also remove "var num=10
", then an undefined error will occur. .
The following is an introduction to JS scope and block-level scope
Scope is always the most important thing in any programming language Heavy because it controls the visibility and life cycle 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 in a pair of curly braces ({ and }) belongs to a block. All variables defined in it are invisible outside the code block. We It's called block 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); }
When you run this code, the error "use an undefined variable:j" will appear. As you can see, the C language has block-level scope because j is defined in the if statement block, so it is inaccessible outside the block.
How does JS behave? Let’s look at another demo:
functin test(){ for(var i=0;i<3;i++){ } alert(i); } test();
When you run this code, "3" pops up ", it can be seen that outside the block, the variable i defined in the block is still accessible. In other words, JS does not support block-level scope, it only supports function scope, and variables defined anywhere in a function are visible anywhere in the function.
那么我们该如何使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 (){ //内容 })();
相关推荐:
The above is the detailed content of Scope and block-level scope in Javascript. For more information, please follow other related articles on the PHP Chinese website!

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.

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 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.

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

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.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.
