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's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.