Implicit global variables
Local variables
Variable declaration hoisting
Name resolution order
Namespace
Conclusion
Although JavaScript supports code snippets created by a pair of curly braces, it does not support block-level scope; only function scope is supported.
function test() { // 一个作用域 for(var i = 0; i < 10; i++) { // 不是一个作用域 // count } console.log(i); // 10 }
Translator's Note: If the left bracket of the return object and return are not on the same line, an error will occur.
(Note: If it is not in an assignment statement, but in a return expression or function parameter, {...} will be parsed as a code segment, not as the literal syntax of the object . If automatic semicolon insertion is taken into account, this may lead to some subtle errors)
// 译者注:下面输出 undefined function add(a, b) { return a + b; } console.log(add(1, 2));
There is no explicit namespace definition in JavaScript, which means that all objects are defined in a Under the globally shared namespace.
Every time a variable is referenced, JavaScript will traverse the entire scope upward until it finds the variable. If the global scope is reached but the variable is still not found, a ReferenceError exception is thrown.
Implicit global variables
// 脚本 A foo = '42'; // 脚本 B var foo = '42'
The above two scripts have different effects. Script A defines variable foo in the global scope, while script B defines variable foo in the current scope.
Again, the above effect is completely different. Not using var to declare variables will result in the generation of implicit global variables.
// 全局作用域 var foo = 42; function test() { // 局部作用域 foo = 21; } test(); foo; // 21
Declaring the foo variable without using the var keyword in the function test will overwrite the external variable with the same name. This may not seem like a big problem at first, but when you have thousands of lines of code, declaring variables without using var can lead to bugs that are hard to track down.
// 全局作用域 var items = [/* 数组 */]; for(var i = 0; i < 10; i++) { subLoop(); } function subLoop() { // subLoop 函数作用域 for(i = 0; i < 10; i++) { // 没有使用 var 声明变量 // 干活 } }
The outer loop will terminate after the first call to subLoop because subLoop overwrites the global variable i. This error can be avoided by declaring the variable using var in the second for loop. Never omit the var keyword when declaring a variable unless this is the desired behavior affecting the outer scope.
Local variables
Local variables in JavaScript can only be declared in two ways, one is as a function parameter, and the other is declared through the var keyword.
// 全局变量 var foo = 1; var bar = 2; var i = 2; function test(i) { // 函数 test 内的局部作用域 i = 5; var foo = 3; bar = 4; } test(10);
foo and i are local variables within the function test, and the assignment to bar will overwrite the variable with the same name in the global scope.
Variable declaration hoisting (Hoisting)
JavaScript will hoist variable declarations. This means that both var expressions and function declarations will be hoisted to the top of the current scope.
bar(); var bar = function() {}; var someValue = 42; test(); function test(data) { if (false) { goo = 1; } else { var goo = 2; } for(var i = 0; i < 100; i++) { var e = data[i]; } }
The above code will be converted before running. JavaScript will hoist var expressions and function declarations to the top of the current scope.
// var 表达式被移动到这里 var bar, someValue; // 缺省值是 'undefined' // 函数声明也会提升 function test(data) { var goo, i, e; // 没有块级作用域,这些变量被移动到函数顶部 if (false) { goo = 1; } else { goo = 2; } for(i = 0; i < 100; i++) { e = data[i]; } } bar(); // 出错:TypeError,因为 bar 依然是 'undefined' someValue = 42; // 赋值语句不会被提升规则(hoisting)影响 bar = function() {}; test();
The lack of block-level scope not only causes var expressions to be moved from inside the loop to the outside, but also makes some if expressions harder to read.
In the original code, the if expression seems to modify the global variable goo, but in fact it modifies the local variable after the promotion rule is applied.
Without knowledge of hoisting, the following code appears to throw a ReferenceError exception.
// 检查 SomeImportantThing 是否已经被初始化 if (!SomeImportantThing) { var SomeImportantThing = {}; }
Actually, the above code works fine because the var expression is hoisted to the top of the global scope.
var SomeImportantThing; // 其它一些代码,可能会初始化 SomeImportantThing,也可能不会 // 检查是否已经被初始化 if (!SomeImportantThing) { SomeImportantThing = {}; }
Translator's Note: There is an article introducing hoisting on the Nettuts+ website, and the code in it is very enlightening.
// 译者注:来自 Nettuts+ 的一段代码,生动的阐述了 JavaScript 中变量声明提升规则 var myvar = 'my value'; (function() { alert(myvar); // undefined var myvar = 'local value'; })();
Name resolution order
All scopes in JavaScript, including the global scope, have a special name this pointing to the current object . There is also a default variable arguments in the function scope, which contains the parameters passed to the function. For example, when accessing the foo variable within a function, JavaScript will search in the following order:
Whether there is a definition of var foo in the current scope.
Whether the function formal parameters use the foo name.
Whether the function itself is called foo.
Go back to the previous scope and start again from #1.
Namespace
A common mistake caused by having only one global scope is naming conflicts. In JavaScript, this can be easily solved with anonymous wrappers.
(Note: Custom arguments parameters will prevent the creation of native arguments objects.)
(function() { // 函数创建一个命名空间 window.foo = function() { // 对外公开的函数,创建了闭包 }; })(); // 立即执行此匿名函数
Anonymous functions are considered expressions; therefore for callability, they are executed first .
( // 小括号内的函数首先被执行 function() {} ) // 并且返回函数对象 () // 调用上面的执行结果,也就是函数对象
There are some other ways to call function expressions. For example, the following two methods have different syntax, but the effect is exactly the same.
// 另外两种方式 +function(){}(); (function(){}());
Conclusion
It is recommended to use an anonymous wrapper (Translator's Note: that is, a self-executing anonymous function) to create a namespace. This not only prevents naming conflicts, but also facilitates the modularization of the program.
Also, using global variables is considered a bad habit. Such code is error-prone and costly to maintain.
The above is the content of JavaScript advanced series - scope and namespace. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

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.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development 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

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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