In-depth analysis of javascript scope (recommended) and javascript

Source: Internet
Author: User

In-depth analysis of javascript scope (recommended) and javascript

The so-called scope can be simply understood as a range (region) that can be read and written. Some js users may say, "js has no block-level scope ", in addition to the global scope, only functions can create scopes. One benefit of scope is that variables can be isolated.

We use some examples to help us understand the scopes in js.

 alert(a); var a = 1; 

If you do not know the scope, you may say that alert has 1 or an error, but it is actually undefined;

Speaking of this, let's first talk about some preparations made before js parses the code line by line,

Before js reads the code line by line, it will do some "pre-resolution" work and find some "small items" in advance. Of course, "js parser" won't look for any data, it is based on var, function, and parameters.

"Js parser" it is relatively "lazy". Before the code is officially run, the variable declared by var will be assigned undefined, that is, var a = undefined; the entire function is regarded as a code block, regardless of the amount of code in it. The parameters will be described later in the example.

After all the preparation work is done, the "JS parser" starts to execute the code line by line. Now we can analyze the example to easily understand why it is undefined.

Let's take a look at the example below.

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

Let's take a look at this.

First, "pre-resolution": the parser will look for var

Read the second row a = undefined;

The fourth row is still a = undefined;

Formally execute the code line by line:

First line alert: undefined

Row 2 a = 1;

Row 3 alert: 1;

Fifth line alert: 2

Next, let's look at the example below.

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

Let's analyze this a little bit.

First, "pre-resolution": the parser will look for var function;

Read the second row a = undefined;

When reading the fourth row, a = function a () {alert (2) ;}// all functions are the entire function block before the code is officially run. The variable has a duplicate name, only one variable is left. If the variable and function have the same name, only the function is left.

When reading the sixth row, a = function a () {alert (2 );}

When reading the eighth row, a = function a () {alert (4 );}

Formally execute the code line by line:

Line 1 alert: function a () {alert (4 );}

The second line a = 1; // The expression can modify the pre-resolution value!

Row 3 alert: 1;

Row 4: The function is not called, skipped;

Fifth line alert: 1;

Row 6 a = 3;

Row 7 alert: 3

The eighth row of function is not called, skipped;

Row 9 alert: 3

:

Continue with the example:

var a = 1;function fn1(){ alert(a); //undefined    var a = 2;}fn1();alert(a); //1

First, "pre-resolution": the parser will find the var function

Read the first row a = undefined;

Read the second row fn1 = function fn1 () {alert (2); var a = 2 ;}

Formally execute the code line by line: the first line a = 1;

The sixth line of the function is called. The function scope is still pre-parsed and then executed row by row.

Pre-parsing in the function: a = undefined;

Run: alert: undefined;

A = 2; // At this time, a is only a in the function scope and does not affect a in the global

After the function is executed, return to the global scope;

Row 7 alert: 1;

Continue:

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

In this example, the only difference in the above example is that function a does not have var and only analyzes the key points.

The third line of alert (a) in the function scope, because the function does not have var, therefore, the "parser" will go to the upper-level scope of the function to search for a (the determination of the upper-and lower-level relationship of the scope depends on the scope in which the function is created and under which scope it is created, at this time, the upper level of the function is the global scope. In the global scope, a = 1. Therefore, the third line is alert: 1, followed by the fourth line, a = 2 assignment, still function scope does not have a, so find a in the upper-level scope, that is, global scope, modify a in global scope, therefore, the global scope will contain a = 2, so the seventh line of alert: 2;

This should be clearly understood, and there is no difference between var.

Next:

 var a = 1; function fn1(a){ alert(a); //undefined  a = 2; } fn1(); alert(a); // 1

The difference between this example and the previous one is that there is an extra parameter, and the role of the parameter is equivalent to a local variable, that is, in the function pre-parsing there will be var a = undefined, so the third row alert: undefined, the fourth line a = 2 is changed to a in the function scope, without affecting a in the global, the seventh line alert: 1;

Next:

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

This example is different from the previous one. In the sixth row of function calling, a real parameter is passed in. In the sixth row, the real parameter a is 1 of the global variable a = 1. When the function is executed, the second row a = 1, so the third row alert: 1, the seventh row alert: 1.

Note the differences between these examples. Do not confuse them.

Next:

var a = 1;function en(){var a = 2;fn();}function fn(){alert(a); //1}en();

A In fn is not declared. The value is "created" in the scope where the function is created, rather than "called" in the scope of the function.

PS: scope and context concepts in JavaScript

Scope and context in javascript are unique in this language, thanks in part to their flexibility. Each function has different variable context and scope. These concepts are the backing of some powerful Design Patterns in javascript. However, this also brings great confusion to developers. The following fully reveals the differences between context and scope in javascript and how to use them in various design patterns.

Context vs Scope

The first problem to be clarified is that context and scope are different concepts. Over the years, I have noticed that many developers often confuse these two terms and incorrectly describe one as another. In all fairness, these terms have become very messy.

Each function call has a corresponding scope and context. Basically, the range is function-based, while the context is object-based ). In other words, the scope is related to the access to variables during each function call, and each call is independent. Context is always the value of the keyword this, which is a reference to the object that calls the current executable code.

The above is the scope (recommended) in javascript introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.