Scopes in JavaScript

Source: Internet
Author: User
Tags visibility

Reproduced

1. Definition

Scope scope
1) an area in which something is executed, manipulated, and controlled
2) When writing a program, the visibility of variables in the program; For example, whether a function can use a variable created by another function.

2. Example Demo

Open Firefox, eject Firebug, and click Console tab. In the Firefox status bar, you can see the >>> prompt in the place to enter.

function fn () {alert (11);}

then enter. All Enron ... What you just did was actually defining a function, fn. Then try:

FN ();

then enter. Get a 11 warning window and then try:

Window.fn (); this. Fn ();

Get the same results? This is because the function fn is a method of the Window object, and the scope of the "This" in the second row actually points to the Window object. But in most cases you don't need to be like this window.myfunction (...) To call a function, which is too cumbersome for programmers to work with.

window Object

The window object is always there, and you can understand it as a browser window object. It contains all the other objects, such as document and all global variables.

You can open firebug, switch to the Script page and enter windowin the New watch expression ... on the right side of Firebug. See what the Window object actually has inside it.

Next, try to find the FN function we defined earlier.

In addition, each frame or IFRAME has its own window object, its own global space.

Understanding Scopes

The content is starting to get a little complicated. Switch to the Firebug Console tab and enter:

var o1 = {testvar:22, fun:functionthis. testvar);}}; var o2 = {testvar:33, fun:functionthis. TestVar); }};

What was the result? You have declared O1 and O2 two objects, each with some properties and methods, but with different values.

Then try:

Fun (); Window.fun (); this. Fun ();

It's a mistake, isn't it? Because the Window object (which is equivalent to this) does not have a fun method. Try the following:

O1.fun (); O2.fun ();

22 and 33 out? Very good!

The next part of the content is the most complex. Based on this primitive function, if you have a large number of objects, you must add this function to each object-obviously repetitive labor. To put it this way, O1.fun is very clear and has taken up one weeks of development time in order to fix it. Imagine the code spreading this variable everywhere, how can you not have a headache? If you want to call (execute) The O1.fun method But this will execute O2, how should it be implemented? Try the following:

O1.fun.call (O2);

Do you understand? When you execute O1 's Fun method, you force the variable this to point to the O2 object, in other words, more rigorously: theo1.fun method runs under the scope of the object O2 .

When you run a function that is a method of an object, you can treat the scope as a variable of this value .

The visibility of the variable

The visibility of variables is closely related to the scope. We have learned that it is possible to declare variables outside of any object, or in global functions (functions are also one of the variables), and more strictly, they are properties of the Global Object window . Global variables are visible everywhere, whether inside or outside the function. If you modify a global variable within a function, other functions will know that the value has been modified.

An object can have its own properties (like the testvarabove), which are allowed to be visible from inside or outside. Try:

alert (O1.testvar); External access to O1 properties TestVar

The demo from inside Access can be found in the fun method of two test objects.

Declared internally with the keyword var , which is equivalent to declaring a local variable (the local declaration is also on a chain, that is, on the scope Chain scope chain):

i =fn2function  ()     {var i =;     alert (i); }fn2 ();

What will you get? That's right, 55. Declaring the variable i in the function fn2 is a local variable (local variable), and the global variable i 44 equals 44 has nothing to do with it. But:

This accesses the global variable i, which shows 44.

Two Nested functions (Scope chain)

1 varTestVar = ' Window property '; 2 varO3 = {3TestVar: ' 3 ',4TESTVAR2: ' 999 ',5Funfunction(){6Alert (' O3: ' + This. TestVar);//' O3 3 '7           varInner =function(){8               //Scope of current object + global scope: Closures9Alert (' O3-inner: ' + This. TestVar); // can be changed to O3.testvar test results  TenAlert (' O3-inner: ' + This. testvar2); OneAlert (' O3-inner: ' +TestVar);  A           }; -Inner ();//window -           //Inner.call (this); O3+window the           //Inner.call (O2); O2+window -        } -     }; -O3.fun ();//you can invoke member variables that are not O3 declared

Here we have another function, which is almost similar to the original function but the difference is the notation of the inner function. Note that the scope in which the intrinsic function is run is different from the scope of the external function. Ext lets you specify the scope of the function when you invoke the function, avoiding the problem of scope.

Here is also the closure: closures, refers to the lexical representation includes non-computed variables of the function, that is, the function can use variables defined outside the function (believe that many small partners in the interview will be asked to closure)

Declaration of a variable

Be sure to add the "var" keyword when initializing the variable, which is a global variable. For instance, in the following example, a variable is written inside the function, but you intend to declare only local variables, but you may actually have a situation where the values of the global variables are overwritten. In the Firebug "DOM" tab, you can see all the global variables by detecting "window". If you find a "K" or "x" variable that proves that you are assigning this variable to an inappropriate scope. See the following example:

vari = 4;varj = 5;varK = 7;varfn =function(){   vari = 6; K= 8;//Notice that there is no var so the meaning of this sentence is given 8 to the variable K! alert (i);//6Alert (j);//5Alert (k + '-1 ');//8-1x = 1;//The function of this sentence has two cases, create all variables x or overwrite (overwrite) all variables x};FN (); alert (k+ '-2 ');//8-2 (note not 7-2)

Unlike the previous example, it is important to note that there is no var keyword in front of k in the function, so instead of declaring a local variable, a value is assigned to the global variable K again. It is also important to note that during the alert method execution, the parameter i is the local variable that is currently found, its value is 6, but the parameter J is not found in the current scope, and is looked up along the scope chain (scope chain) . Always find the global variable until the J.

Summarize:

    1. All members are scoped to window
    2. The scope of an object can be passed by call
    3. the variable declaration inside the function : a local variable with VAR, or a global variable.
    4. Functions declared inside the function, The default scope points to window.

Scopes 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.