


Detailed explanation of JavaScript variable declaration and local variable substitution of global variables
Those defined outside the function body are global variables, and those defined inside the function body are local variables. The definition here refers to the declaration through var.
JavaScript has the concept of implicit globals, which means that any variable you do not declare will become a global object property. For example:
function test(){ myname = "huming"; alert(myname); } test(); // "huming" alert(myname); //"huming"
The two results are the same, indicating that myname is a global variable.
So, is there any difference between implicit global variables and explicitly defined global variables? . The answer is definitely yes, look at the following example:
// 定义三个全局变量 var global_test1 = 1; global_test2 = 2; // 反面教材 (function () { global_test3 = 3; // 反面教材 }()); // 试图删除 delete global_test1; // false delete global_test2; // true delete global_test3; // true // 测试该删除 alert(typeof global_test1); // "number" alert(typeof global_test2); // "undefined" alert(typeof global_test3); // "undefined"
As can be seen from the above example: global_test1 defined by var outside the function cannot be deleted, and global_test2 and global_test3 that are not defined by var are both deleted. Deleted (whether created within the function body or not).
In summary, global variables declared through var outside the function cannot be deleted, but implicit global variables can be deleted.
It should be noted here: JavaScript has a behavior called "hoisting" (suspending/top parsing/pre-parsing).
Let’s illustrate with an example:
var myname = "huming"; //声明全局变量 function test() { alert(myname); var myname = "local_huming"; alert(myname); } test();
Do you guess that the contents of the two alerts are consistent? ? Obviously inconsistent, needless to say consistent. . Actual output is: "undefined", "local_huming".
The above example is equivalent to
var myname = "huming"; //声明全局变量 function test() { var myname; alert(maname);<br> myname = "local_huming"; alert(myname); // "local" } test();
The myname output by alert for the first time is not the global variable you think, but a local variable in the same scope (a function body) with it. . Although it has not been declared, it is treated as such. This is called "hoisting".
This should make it clear. When you use a variable in a function body and redeclare it later, an error may occur.
Writing specifications:
function test() { var a = 1, b = 2, c = a + b, d = {}, e, f; // function body... }
The advantage is:
1. All local variables are defined at the beginning of the function, making it easy to find;
2. Prevent variables from being Define the logic error used before.
How to replace?
On the issue of how to improve JavaScript performance, the most commonly heard suggestion is to use local variables instead of global variables. This advice has always stuck with me and never been questioned in my nine years of working in web development, and the basis for this advice comes from JavaScript's handling of scoping and identifier resolution. (identifier resolution) method.
First of all, we must make it clear. The function is exactly the object of the function in JavaScript. The process of creating a function is actually the process of creating an object. Each function object has an internal property called [[Scope]], which contains the scope information when the function was created. In fact, the [[Scope]] attribute corresponds to a list of objects (Variable Objects), and the objects in the list can be accessed from inside the function. For example, if we create a global function A, then A's [[Scope]] internal property contains only one global object (Global Object), and if we create a new function B in A, then B's [[Scope] ] attribute contains two objects, the Activation Object object of function A is in the front, and the global object (Global Object) is in the back.
When a function is executed, an executable object (Execution Object) will be automatically created and bound to a scope chain (Scope Chain). The scope chain will be established through the following two steps for identifier resolution.
First, copy the objects in the internal properties of the function object [[Scope]] to the scope chain in order.
Secondly, when the function is executed, a new Activation Object object will be created. This object contains the definitions of this, parameters (arguments), and local variables (including named parameters). This Activation Object object will Placed at the front of the scope chain.
During the execution of JavaScript code, when an identifier is encountered, it will be searched in the scope chain of the execution context (Execution Context) based on the name of the identifier. Starting from the first object in the scope chain (the Activation Object object of the function), if it is not found, search for the next object in the scope chain, and so on, until the definition of the identifier is found. If the last object in the scope, which is the Global Object, is not found after searching, an error will be thrown, prompting the user that the variable is undefined. This is the function execution model and identifier resolution (Identifier Resolution) process described in the ECMA-262 standard. It turns out that most JavaScript engines are indeed implemented this way. It should be noted that ECMA-262 does not mandate the use of this structure, but only describes this part of the function.
The above is the detailed content of Detailed explanation of JavaScript variable declaration and local variable substitution of global variables. For more information, please follow other related articles on the PHP Chinese website!

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

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
