JavaScript variable scope and closure_javascript skills
Scope JavaScript variable scope is divided according to functions. In order to quickly understand its characteristics, we will demonstrate it through an example.
Example 1:
<script type="text/javascript"> var i = 1; // 弹出内容为 1 true 的提示框 alert(window.i + ' ' + (window.i == i)); </script>
Analysis:
The variables defined globally are actually the attributes of the window object.
As can be seen from the above example, when we define global variables, the window object will generate a corresponding attribute. How to prevent our code from generating this attribute? See the example below.
Example 2:
<script type="text/javascript"> var document = 1; window.onload = function(){ alert(document); } // 弹出内容为 1 的提示框 alert(window.document); </script>
This is a situation we don’t want to see. We can do this:
<script type="text/javascript"> function test(){ var document = 1; window.onload = function(){ alert(document); } } test(); // 弹出内容为 [object] 的提示框 alert(window.document); </script>
In order to make the code more concise, we can do this:
<script type="text/javascript"> (function(){ var document = 1; window.onload = function(){ alert(document); } })(); // 弹出内容为 [object] 的提示框 alert(window.document); </script>
Analysis:
This form of running anonymous methods is often seen in mainstream JavaScript frameworks. This can avoid generating unnecessary attributes of the window object and reduce the possibility of conflicts.
Example 3:
<script type="text/javascript"> (function(){ if('1' == '1'){ var i = 1; } // 弹出内容为 1 的提示框 alert(i); })(); </script>
Analysis:
The scope of the variable is the entire function, not the {} block.
Example 4:
<script type="text/javascript"> var i = 1; // 弹出内容为 1 的提示框 alert(i); var i = 2; // 弹出内容为 2 的提示框 alert(i); </script>
Analysis:
A variable can be redefined, which seems a bit strange, because this does not work in many other languages.
Example 5:
<script type="text/javascript"> function test(){ i = 1; } test(); // 弹出内容为 1 的提示框 alert(window.i); </script>
Analysis:
If an uninitialized variable is assigned a value, then this variable will be used as a global variable.
Example 6:
<script type="text/javascript"> window.onload = function(){ var i = 1; function test(){ alert(i); } // 弹出内容为 1 的提示框 test(); } </script>
Analysis:
Internal functions can access variables of external functions, which leads to a new concept, that is closure.
Closure
What is a closure? Simply put, it is a function A whose internal function B can access the variables defined in A, even if function A has terminated. Let’s learn about it through examples.
Example 7:
<script type="text/javascript"> window.onload = function(){ var i = 1; window.onunload = function(){ alert(i); } } </script>
Analysis:
When the entire page is loaded, the onload event will be triggered. This onload event method registers a method for the onunload event of the window. In this method The variables declared in the onload event method are used, and then the onload event method ends. At this time, we click to close the window, and a prompt box with a content of 1 will pop up, indicating that the onunload event method successfully called the variables declared in the onload event method.
In order to further understand the characteristics of closures, look at the following example
Example 8:
<script type="text/javascript"> function initX(oarg){ // 定义一个变量 var x = oarg; // 定义一个显示变量的方法 var funGet = function(){ alert(x); } // 定义一个对变量进行修改的方法 var funSet = function(iarg){ x = iarg; } // 返回这两个方法 return [funGet,funSet]; } // 运行一个方法实例,返回值为包含 get 和 set 方法的数组 var funArr = initX(1); // 得到 get 方法 var funGet = funArr[0]; // 得到 set 方法 var funSet = funArr[1]; // 运行 get 方法,显示initX方法实例内的 x 变量,结果为 1 funGet(); // 运行 set 方法,对initX方法实例内的 x 变量进行赋值 funSet(2); // 运行 get 方法,显示initX方法实例内的 x 变量,结果为 2 funGet(); </script>
Analysis:
When the internal function calls the variable defined by the external function, in fact The reference is to the memory block of this variable, so when we call the internal function, the referenced variable value is the actual content of the current variable.
Although the closure function is powerful, it can also cause us trouble if we are not careful. See the example below.
Example 9:
<button id="main">run</button> <script type="text/javascript"> (function(){ var obj = document.getElementById("main"); var funArr = ['onclick','onkeypress']; for(var i=0; i<funArr.length; i++){ var temp = funArr[i]; obj[temp] = function(){ alert(temp); } } })(); </script>
The original intention of writing the code is to register click events and key events for the button whose id is main. The content of the event is to pop up a prompt box with the event name respectively. But the result is a bit strange. The prompt boxes of the two events are all onkeypress. According to the principle of closure, if we analyze carefully, we will find that when the two event methods are called, the temp variable points to the content of funArr[1]. We can Modify this way to solve this problem:
<button id="main">run</button> <script type="text/javascript"> (function(){ var obj = document.getElementById("main"); var funArr = ['onclick','onkeypress']; for(var i=0; i<funArr.length; i++){ (function(){ var temp = funArr[i]; obj[temp] = function(){ alert(temp); } })(); } })(); </script>
Put the code in the for loop into a function, so that each loop will generate a function instance and let the function instance record each value in the funArr array , thus avoiding the problems encountered above.

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.

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.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools
