JS Scope Use method description

Source: Internet
Author: User
Tags closure

A face test to explain 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're going to analyze this output directly, in sequence,

Order of execution

  code is as follows copy code

1.FOO.PROTOTYPE.ABC = function () {alert (' Alisoft ');}

After that, we can use OBJ.ABC (), the prototype prototype, we can see this prototype prototype inheritance

2.FOO.ABC = function () {alert (' Yahoo ');}

Alert Yahoo

3.var obj = new Foo ();

Creates an instance of Foo with obj, and executes the Foo function, which is obj.abc () = function () {alert (' Alimama ')}

4.FOO.ABC = function () {alert (' Alibaba ')}

FOO.ABC is a static method of the Foo class that executes the code fragment FOO.ABC = function () after the Foo is instantiated.

Overwrite the original FOO.ABC = function () {alert (' Yahoo ');}, so Foo.abc () output Alibaba

5.THIS.ABC = function () {alert (' Alimama ')}

This sentence assigns function () {alert (' Alimama ') to OBJ.ABC, so obj.abc output Alimama

6.ABC = function () {alert (' Alipay ')}; var abc = function () {alert (' Taobao ')};

The two sentences are analyzed together, if there is no next sentence, then ABC is a global variable, ABC output Alipay

But since the next line of VAR abc, the scope of ABC is limited to the Foo class, so the external ABC () will show undefined.

So the answer is

Alimama

Alibaba

Undefine

Closures: An expression (usually a function) that represents a variable that can access and manipulate other local scopes.

Scope

Represents the area in which a variable or function works, and refers to the context in which they are executed. There are two kinds of JavaScript total scopes: global scope and local scope. Local scopes in JavaScript are differentiated by function.

The code is as follows Copy Code

var global = "11"; Global scope

function Fun () {

var local = "22"//Native Scope 1

}

function fun2 () {

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

for (Var i=0;i<100;i++) {

Local Scope 2

}

}

Unlike the Java language, for loops are also a scope, in JavaScript the local scope is differentiated by function. The scope concept of JavaScript resembles a lexical scope.
Lexical scopes: Also called static scopes, the scope of a variable is determined when it is defined, not when it is executed. That is, the lexical scope depends on the source code, through static analysis can be determined.

Scope chain

Like the prototype chain, the scope chain of JavaScript is queried sequentially. When you access a variable, you first see if the local scope has this variable, and if not, then look up to the global scope in ascending-level scopes. If the global scope does not have this variable, the variable will be declared in the global scope. Like 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 that represents the environment in which the current code executes. That is the object of the this variable; it's difficult to understand, just look at an example:

The code is as follows Copy Code

function Test () {

Console.log (this);

}

Test (); Window

New Test ();//object


When you execute Test (), the context object at this point is window, which is the global object of JavaScript! When you execute the new test (), a new object is created, and the context object that executes the Test function is objects. If you don't understand, you can look at me. How to implement object-oriented programming with JavaScript a section of the code is as follows:

The code is as follows Copy Code

function NewObj (fun,arguments) {

var o = {};

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

o.__proto__ = Fun.prototype;

Fun.apply (o, arguments);

return o;

}

}


This is mainly the simulation of the new function operation, you can see Fun.apply (o,arguments), this step, the role of apply is to specify the execution of the fun function and its context is O, input parameter is arguments object. So the result of new Test () is object.

Closed Bag

An expression that represents a variable that can access and manipulate other internal scopes (usually a function). A simple description of the language is that the function that can manipulate other local scope variables is the closure. Or look at 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

Consider the logic in the Java language or other non-closures language first. When the fun function completes, its internal variable I should be released, and the output error occurs when the closure function executes and invokes I (since I was not declared). But the value is printed in JavaScript, thanks to closures. When the fun () function is executed, the closure is created. I was not released at this time, and closure can still be accessed.

Also note that the closure is essentially an expression (usually a function), so the closure is defined when the function is generated. (The 3rd line of the above code defines the closure)!

The function of closure

The biggest function of closures is to prevent external programs from randomly accessing internal variables, which can only be accessed and manipulated through the provided interfaces. such as the implementation of one of the following registers:

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 (). Add (). Add ();

Console.log (Counter.get ()); 3


If the variable is not exposed directly to the closure, a bug can 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 will be attributed to + + + these two operators.


To give 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 the first hint of a warning [object window], and then the 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, then define an obj function object, add a private field name to it, and add a static method to it Objtest (), This function then points directly to the test () function.

The test () and Obj.objtest () methods are called separately, the first warning box prompts the Window object, and the second prompts the code for the function of obj that we define. This shows that the value of this is different when the test function is executed two times!

This means that when the object that calls the function is different, the inside of the This keyword refers to objects that are different. What is noteworthy here is that JavaScript is an object-based language, and when our variables or functions are defined under the root of the <script></script> tag, the corresponding attributes or methods are added to the Window object. So when we define a function by using function test () {} code, we actually add a new function, the window.test () function, to the Window object.
We can do an experiment:

The code is as follows Copy Code

function Test () {


alert (this);

}

alert (test===window.test);

The warning box prompts for true, which means that when we call test () This function is equivalent to calling Window.test (). So when we call the test () function, the object that calls the function is actually a window object, and this refers to the Window object, so the warning window that pops up at alert (this) is [object window]. We will obj.objtest=test the equivalent of pointing obj.objtest () to test (), so when we call the Obj.objtest () function, we call the test () function in obj, so now this refers to the Obj object, The hint is that the function of obj is the code we see.

Speaking of this should also explain the similar, perhaps the above example is too abstract to imagine it can be used in any case, then we now assume a demand, do a close to practical example.
Let's say that all of the hyperlinks in our page are changed to red after the click and are implemented in JavaScript. The general idea should be to get all the <a> tags in the page, and then go through all the <a> tags, to each register a click event, after the event triggered we set its color value to red.
The sample code is as follows:

  code is as follows copy code

 

function ChangeColor () {

 

this.style.color= ' #f00 ';

 

}

 

//initialization, registering events for all a tags

 

Function init () {

 

Var customlinks= document.getElementsByTagName (' a ');

 

For (i in customlinks) {

 

//You can also use event listeners to register events

 

//Because browsers such as IE,FF may require more code, You can write your own

 

Customlinks[i].onclick=changecolor;

 

}

 

}

 

Window.onload=init;


Add this code to the HTML document and add some hyperlinks to the document, and when the hyperlink clicks the color turns red, the This keyword in the ChangeColor () function we defined here refers to the current hyperlink when you click on the hyperlink to send the function. If you call the ChangeColor () function browser directly, you will be prompted to error: ' This.style ' is a null or not a object or a undefined.

I wonder if this will make you understand the This keyword in JavaScript when you're reading the article? Or are you getting impatient? (:P)

In fact, in order to really have a deeper understanding of this problem, you must have a deep understanding of the scope and scope chain of JavaScript.

A scope, as its name implies, refers to the code space in which a property or method has access, and simply the scope of the variable or method that it applies to the code. In most oop, there are public,private,protect three scopes, which are not explained in detail in the three scopes, and there should be an in-depth understanding of OOP experience. What I'm going to say here is that these three scope types are almost meaningless to JavaScript because there is only one public scope in JavaScript, and the scope in JavaScript is maintained in a 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);

As we explained earlier, the TEST1 variable here is equivalent to a window property, so it works throughout the window scope, and Test2 is declared inside the example () function, so its scope is maintained within the example () method, If you invoke the Test2 browser outside of the function, you will be prompted for an error. It is not a problem to call Test1 inside example ().
Based on this, let's give another example:

The code is as follows Copy Code


var test= ' globle variable ';

function Example () {

var test= ' example variable ';

}

Example ();

alert (test);

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

Speaking of which, there is another concept involved, that is the concept of the scope chain. A scope chain is a path that can determine the value of a variable. As you can see from the example above, the VAR keyword is used to maintain the scope chain, and if the variable uses the var keyword declaration then he can be considered as the endpoint of the scope chain. The definition of the formal parameters of the same function can also play a similar role.

Speaking of which, do you have a clearer understanding of this elf-freak guy? According to its simple interpretation, this always points to the object that calls its function, and by the scope and scope chain, we will clearly determine the true face of this. A simple change in the beginning of 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 think will be prompted? You can run a try (:P);

Since this is changed based on the change of the object that called its function, can we force it to change its calling object? The answer is yes, the future article will introduce this part of the content, as well as JavaScript different types of data members to implement, closures and other concepts.

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.