Js scope usage instructions

Source: Internet
Author: User

Js scopes are used in a variety of ways and different results are produced in a single detail. Next I will summarize some instructions on js scopes. If you need them, please refer to them.

This is an interview question to introduce the js scope in detail.

The Code is as follows: Copy code

Function foo (){
Foo. abc = function () {alert ('alibaba ')}
This. abc = function () {alert ('alimama ')}
Abc = function () {alert ('alipay ')};
Var abc = function () {alert ('taobao ')}
}
Foo. prototype. abc = function () {alert ('alisoft ');}
Foo. abc = function () {alert ('yahoo ');}
Var obj = new foo ();
Obj. abc ();
Foo. abc ();
Abc ();


We will analyze the output in order,

 

Execution sequence

The Code is as follows: Copy code

1. foo. prototype. abc = function () {alert ('alisoft ');}

// In this way, we can use obj. abc (); if we do not understand the prototype, we can see that the prototype inherits

2. foo. abc = function () {alert ('yahoo ');}

// Alert yahoo

3. var obj = new foo ();

// Create a foo instance obj and execute the foo function, that is, obj. abc () = function () {alert ('alimama ')}

4. foo. abc = function () {alert ('alibaba ')}

// Foo. abc is a static method of the foo class. After the foo class is instantiated, the code snippet foo. abc = function () is executed ()

// Overwrite the original foo. abc = function () {alert ('yahoo ') ;}, so foo. abc () Outputs alibaba

5. this. abc = function () {alert ('alimama ')}

// This sentence assigns function () {alert ('alimama ') to obj. abc, so obj. abc outputs Alimama

6. abc = function () {alert ('alipay')}; var abc = function () {alert ('taobao ')};

// These two sentences are analyzed together. If there is no next sentence, abc is a global variable, and abc outputs alipay.

// However, because the scope of abc is restricted to the foo class after the next var abc statement, the external abc () will display undefined.

 

Then, the answer is

Alimama

Alibaba

Undefine

Closure: The expression (usually a function) that can access and operate on variables in other local scopes ).

Scope

It indicates the region in which variables or functions work and the context in which they are executed. There are two types of Javascript scopes: global and local. In Javascript, local scopes are differentiated by functions.

The Code is as follows: Copy code

Var global = "11"; // global scope

Function fun (){

Var local = "22"; // local scope 1

}

Function fun2 (){

Var local2 = "22"; // local scope 2

For (var I = 0; I <100; I ++ ){

// Local scope 2

}

}

 

Unlike Java, A for loop is also a scope. In Javascript, local scopes are differentiated by functions. The concept of Javascript scope is similar to that of lexical scope.
Lexical scope: it is also called static scope. The scope of a variable is determined during definition rather than execution. That is, the lexical scope depends on the source code and can be determined through static analysis.

Scope chain

Similar to the prototype chain, the Javascript scope chain is also queried in order. When accessing a variable, first check whether the local scope has this variable. If not, search for the local scope in the upper-level until the global scope. If the global scope does not have this variable, it will be declared in the global scope. The following code:

The Code is as follows: Copy code

Function f (){

Name = "global ";

Var local = "local ";

}

F ();

Console. log (name); // global

Console. log (local); // undefine


The name variable is declared in the global scope.

Context

It can also be understood as a context object, indicating the environment in which the current code is executed. This is the object referred to by the this variable. It is difficult to understand this. Let's look at an example:

The Code is as follows: Copy code

Function Test (){

Console. log (this );

}

Test (); // window

New Test (); // Object


When Test () is executed, the context object is window, that is, the global object of Javascript! A new Object is created when new Test () is executed. The context Object for executing the Test function is the Object. If you still don't understand it, you can refer to the following code in my article on how to implement object-oriented programming using Javascript:

The Code is as follows: Copy code

Function newObj (Fun, arguments ){

Var o = {};

If (Fun & amp; typeof Fun = "function "){

O. _ proto _ = Fun. prototype;

Fun. apply (o, arguments );

Return o;

}

}


 

This is mainly a simulation of new function operations. You can see Fun. apply (o, arguments); in this step, apply is used to specify the execution of the Fun function and set its context to o, and the input parameter to the arguments object. Therefore, the result of new Test () is an Object.

Closure

Expression that represents the ability to access and operate on variables in other internal scopes (usually a function ). In a simple language, the function that can operate other local scope variables is the closure. Check the Code:

The Code is as follows: Copy code

Function fun (){

Var I = 1;

Return function (){

I ++;

Console. log (I );

}

}

Var closure = fun ();

Closure (); // 2

Closure (); // 3

Follow the logic of Java or other non-closure languages. When the fun function is executed, its internal variable I should be released. When the closure function is executed again and I is called, an error is returned (because I is not declared ). However, a value is printed in Javascript, all thanks to the closure. When the fun () function is executed, the closure is created. At this time, I is not released, and closure can still be accessed.

Note that the essence of a closure is an expression (usually a function), so the closure is defined during function generation. (The first line of the code above defines the closure )!

Function of closure

The biggest function of closures is to prevent external programs from accessing internal variables at will. They can only access and operate through the provided interfaces. The following is an implementation of a counter:

The Code is as follows: Copy code

Var counter = (function (){

Var I = 0;

Return {

Add: function (){

I ++;

Return this;

},

Get: function (){

Return I;

}

}

})();

Counter. add ();

Console. log (counter. get (); // 3


If variables are directly exposed without closure, the following issues may occur:

The Code is as follows: Copy code

I = 0;

Function add (){

I ++;

}

Add ();

Add ();

I + = "1 ";

Add ();

Console. log (I); // 22

As for why such a strange result is generated, it is necessary to return to the + = and ++ operators.


Here is a simple example:

The Code is as follows: Copy code

Function test (){

 


Alert (this );

 

}

 

Var obj = function (){

 

Var name = 'testobj ';

 

}

 

Obj. objTest = test;

 

Test ();

 

Obj. objTest ();


Put this code in HTML to run this page. You will see a warning [object window] First, and a second warning.

 

The Code is as follows: Copy code

Var obj = function (){

 


Var name = 'testobj ';

 

}


We first define a test () method, and call the alert () method inside the method to display this, and then define an obj function object, add a private field name to it, and add a static method objTest () to it. This function directly points to the test () function.

Call the test () and obj. objTest () methods respectively. The first warning box prompts the Window object, and the second prompt shows the code of the obj function we have defined. This indicates that the value of this is different when the test function is executed twice!

This indicates that when the objects that call a function are different, the internal this keyword indicates different objects. It is worth noting that Javascript is an object-based language, when our variables or functions are defined under the root of the <script> </script> label, they are equivalent to adding corresponding properties or methods to the window object, so when we use the function test () {} Code to define a function, it is equivalent to adding a new function to the window object, that is, window. test () function.
We can do an experiment:

 

The Code is as follows: Copy code

Function test (){

 


Alert (this );

 

}

 

Alert (test = window. test );

The warning box prompts true, which means that when we call the test () function, it is equivalent to calling window. test (). Therefore, when we call the test () function, the object that calls this function is actually a window object, and this refers to a window object, so we use alert (this) the pop-up warning Window content is [object Window]. We set obj. objTest = test is equivalent to obj. objTest () points to test (), so when we call obj. the objTest () Function calls the test () Function in obj, so now this refers to the obj object, prompting that the obj Function is the code we see.

This should be explained almost as well. The above example may be too abstract and cannot be imagined when it can be used. Now let's assume a requirement, let's look at a practical example.
Assume that the color of all hyperlinks on the current page should be changed to red after clicking, and implemented in Javascript. The general idea is to obtain all the <a> labels on the page, traverse all the <a> labels, and register a click event for each of them, after an event is triggered, we set its color value to red.
The sample code is as follows:

The Code is as follows: Copy code

 

Function changeColor (){

 

This. style. color = '# f00 ';

 

}

 

// Initialize and register events for all a tags

 

Function init (){

 

Var customLinks = document. getElementsByTagName ('A ');

 

For (I in customLinks ){

 

// You can also use the event listener to register events

 

// To be compatible with IE, FF, and other browsers, you may need more code.

 

CustomLinks [I]. onclick = changeColor;

 

}

 

}

 

Window. onload = init;


Add this code to the HTML document and add some hyperlinks to the document. When the hyperlink is clicked, the color turns red. Here we define changeColor () when you click a hyperlink in a function to trigger a function, this keyword indicates the current hyperlink. If you directly call the changeColor () function browser, an Error is reported, indicating that 'this. style' is null or not an object or undefined.

I don't know if I can help you understand the this keyword in Javascript when reading the article? Or are you impatient? (: P)

In fact, to have a deeper understanding of this issue, we must have a deeper understanding of the Javascript scope and scope chain.

Scope, as its name implies, refers to the code space where an attribute or method has access permissions. Simply put, this variable or method applies to the code. In most OOP projects, there are three scopes: public, private, and protect, which are not explained in detail here. If you have OOP experience, you should have an in-depth understanding. Here I want to talk about the three scope types, which are almost meaningless to Javascript, because Javascript only has one public scope and the scope in Javascript is maintained in the function. For example:

The Code is as follows: Copy code


Var test1 = 'globle variable ';

 


Function example (){

 

Var test2 = 'example variable ';

 

Alert (test1 );

 

Alert (test2 );

 

}

 

Example ();

 

Alert (test1 );

 

Alert (test2 );

 

According to our previous explanation, the test1 variable here is equivalent to an attribute of window, so it will take effect in the entire window scope, while test2 is declared in the example () function, therefore, its scope is maintained inside the example () method. If test2 is called outside the function, an error is prompted. Test1 is called in example.
Here is another example:

The Code is as follows: Copy code


Var test = 'globle variable ';

 

Function example (){

 

Var test = 'example variable ';

 

}

 

Example ();

 

Alert (test );

 

What is the result of this example? Yes, the warning box will prompt "globle variable", because the test variable in the example () function is only in the internal scope and does not affect the external test variable. What if we remove the var keyword of the test variable in example? You can try it on your own.

This involves another concept, namely the scope chain. The scope chain is the path where variable values can be determined. The preceding example shows that the var keyword is used to maintain the scope chain. If the variable uses the var keyword declaration, it can be viewed as the end point of the scope chain. The definitions of the same function parameters also play a similar role.

Speaking of this, do you have a clear understanding of this weird genie? According to its simple interpretation, this always points to the object that calls the function where it is located. Based on the scope and scope chain, we will clearly determine the true face of this. Next, let's start with a simple change in that example:

The Code is as follows: Copy code

Function test (){

 


Alert (this );

 

}

 

Var obj = function (){

 

Var name = 'testobj ';

 

}

 

Obj. objTest = test;

 

Obj. objTest2 = function (){

 

Test ();

 

}

 

Test ();

 

Obj. objTest ();

 

Obj. objTest2 ();

 


What do you expect to prompt? You can run it for a moment (: P );

Since this is changed based on the change of the object in which the function is called, can we force change the object to be called? The answer is yes. later articles will introduce this part, as well as the implementation methods and closures of different types of data members in Javascript.

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.