search
HomeWeb Front-endJS Tutorialjs parsing order scope strict mode parsing

js parsing order scope strict mode parsing

Oct 23, 2017 am 09:10 AM
javascriptScopeorder

1. The parsing order of javascript

We all understand that the execution order of the code is from top to bottom, but in fact it is not like this. Let's take a look at the code below.


1 alert(a);
2 var a = 1;

If the execution order is from top to bottom, and an a pops up on top, the browser will think that it is executed from top to bottom, then when it alerts (a) When, he will find that there is no such thing, then he will report an error, but in fact the result he pops up is undefined. The return value is undefined, indicating that a is not defined, that is, it is not assigned a value. Now let me explain the parsing order of javascript.

 1. The declarative keywords in ES5

 var will have variable promotion

  function and also have the effect of declaring variables.

 2. Parsing order

  1. Find the declaration var, function declaration: only declare variables, not including assignments.

2. Execute

Note: The above two steps are followed from top to bottom. When executing the equal sign, look to the right side of the equal sign first.

Note: When a variable declared by function has the same name as a variable declared by var, the variable weight of function will be higher than that declared by var.

It will be much clearer with a few more examples below, but before looking at the examples, you need to know what scope is.

2. Scope

Scope is: the scope of action is divided into the following two types

 1. Global scope

 2. Function effect Domain

The difference between the two is analyzed carefully in the following example.

3. Let’s look at a few examples to analyze the steps of the execution sequence

1. The first example:


var x = 5;
    a();    
function a(){
        alert(x);        
        var x = 10;
    }
alert(x);

Analysis process

1. Find the declaration (see global scope)

var x;

function a(){}

2. Execute

  x = 5; , look for the statement var x; (function scope)

       2. Execute

        alert(x); This Then the thing that pops up is undefined;

  5

2. The second example

<p style="margin-bottom: 7px;">a() function a(){<br/>    alert(x);    <br/>    var x = 10;<br/> }<br/>alert(x);<br/></p>

The parsing process is the same as the above example

1. Find the statement

  function a(){}


 2. Execution

  a()----------------------- -->Function

       1. Find the declaration

       var x;

          2. Execute

                          

##                         

##                                                                  �                  �  −・・ ##      x = 10; ## So the pop-up content of the browser is undefined error

I believe that everyone who has read these two examples has a clear understanding of this parsing process. If you still don’t understand it well, it is recommended to read it again. .

The following introduces a few things that need attention. Let’s go directly to the example

3. The third example

As mentioned earlier, when the variables declared by function and the variables declared by var overlap When named, the variable weight of function will be higher than that declared by var. Let’s take an example to prove it

alert(a)function a() {
    alert("函数")
}var a = 1;  
alert(a)

Parsing process

1. Find the statement

function a(){}

var a;

2. Execute


alert(a) As mentioned earlier, the function declaration has a higher weight than the var declaration, so when this is executed, it will pop up the function block (function body )

 a = 1;

  alert(a);   What pops up here is 1

  So the final result is function block 1; .Fourth example

The child scope can look for variables from the parent scope until it reaches the global scope, but not vice versa. If the child scope has the same variable, then he will use his own and will not ask his father for it.

var a = 5;function fn() {
    alert(a)
}

fn()

Parsing process

1. Find the statement

var a;

function fn(){}

 2. Execution

 a = 5;


  fn()----------------------- ---------------> Function

                     alert(a);  他这里没有a 所以去找爸爸要。  a = 5;   所以弹窗是  5

  所以最后结果为  弹窗5

  下面看一下爸爸会不会去找儿子要东西


function fn(){    
      var b = 5; 
    return b;    
}
fn();
alert(b);

  1.寻找声明

    function fn(){}

  2. 执行

    fn()----------------------------------------> 函数

                      1.寻找声明

                        1.var b;

                      2.执行

                        return b;

  alert(b);   //我们看一下返回值是多少   b is not defined   他说b没有被定义,说明父作用域不可以向自作用域去寻找变量。

 5. 第五个例子

  当一个变量无中生有时,不管从哪个作用域出来的,统统归到window下,下面看两个例子


  fn();
  alert(a);  var a = 0;
  alert(a);  function fn(){     var a = 1;
  }

这一个例子应该可以自己分析了  最后的结果是  undefined   0

我们再来看一下下面这个你会很吃惊


  fn()
  alert(a)  
  var a = 0;
  alert(a);  
  function fn(){
      a = 1;
  }

  明明都一样,我吃惊什么 返回值不是还是 undefined 和 0 吗

  但是你有没有发现倒数第二行 上面的声明了 下面的没有声明,来解析一波

  1.寻找变量

    var a;

    function fn(){}

  2.fn()---------------------------->函数

          a = 1;  这个时候就说到了那一点,无中生有的变量,统统归到window下面

  所以下面的执行过程

  alert(a)    这里的弹窗就是  1 了

   a = 0;

     alert(a)   弹出 0

  所以最后的结果是   1       0 

四、严格模式

  严格模式下的代码执行时,非常严格

  变量不允许无中生有

  意义:规范代码开发的流畅,逻辑


"use strict"a = 1;
alert(a);

当我们写后面两句代码的时候不会报错和出现问题,但是当我们加上第一句代码的时候,我们在这样写的时候就会报错了。所以我们还是按照规范的标准来,提高自己的能力

五、可能好多人做了上面的例子感觉不太过瘾,下面我再给出几个例子,可以自己去分析分析,我会在最后面给出答案。

1. 第一个例子    //  10 报错


var a = 10;
alert(a);
a()function a(){
    alert(20);
}

2.第二个例子   undefined 1 0


var a = 0;    
function fn(){
        alert(a);        
        var a = 1;
        alert(a);
    }
    fn();
    alert(a);

3.第三个例子 当同样的声明同样的名字重复时,后面写的会覆盖前面写的  //2  1  1  3


 a()    var a = function(){
        alert(1)
    }
    a();    function a(){
        alert(2);
    }
    a();    var a = function(){
        alert(3);
    }
    a()

The above is the detailed content of js parsing order scope strict mode parsing. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

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.

Safe Exam Browser

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.