Javascript learning notes function (6): Role scope and namespace Basics

Source: Internet
Author: User
This article mainly describes the differences between the scope and namespace in javascript, which is very detailed. We recommend it to you here, and hope your friends can gain some benefits in the previous introduction, we already know that Javascript has no block-level function, and only function-level scope.

The Code is as follows:


Function test () {// a scope
For (var I = 0; I <10; I ++) {// not a scope
// Count
}
Console. log (I); // 10
}

No namespace is displayed in Javascript, which means everything is defined in the global scope. Every time a variable is referenced, Javascript traverses the entire global scope until the variable is found. If the variable is still not found in the traversal of the complete global scope, a ReferenceError is thrown.

Enter the image description

Implicit global variables

The Code is as follows:


// Script
Foo = '42 ';
// Script B
Var foo = '42'

The two examples above have different effects. The first defines the variable foo in the global scope, and the second defines the variable foo in the current scope.
We must note that if the keyword var is not used, it will bring unexpected effects.

The Code is as follows:


// Global scope
Var foo = 42;
Function test (){
// Local scope
Foo = 21;
}
Test ();
Foo; // 21

Because var is not used to define the variable foo in the function test, it will overwrite the global variable foo outside the function. Although it does not seem to be a big problem, if there are thousands of lines of code, this will be a hard-to-trace bug.

The Code is as follows:


// Global scope
Var items = [/* some list */];
For (var I = 0; I <10; I ++ ){
SubLoop ();
}
Function subLoop (){
// Scope of subLoop
For (I = 0; I <10; I ++) {// missing var statement
// Do amazing stuff!
}
}

In the above example, the External Loop will be stopped at the first execution, because the variable I in the subloop function will overwrite the global variable I. We only need to add a var inside the function to avoid this error, so we must not forget to add the keyword var when defining the variable. Unless we do want to have an impact on external global variables.

Local variable

In Javascript, local variables can only be generated in two ways. One is declared by the keyword var, and the other is used as the form parameter of the function.

The Code is as follows:


// Global scope
Var foo = 1;
Var bar = 2;
Var I = 2;
Function test (I ){
// Local scope of the function test
I = 5;
Var foo = 3;
Bar = 4;
}
Test (10 );

In this case, the variables I AND foo in the test function are local variables, while bar will overwrite the external global variable bar.

Hoisting)

Javascript will promote the variable declaration, which means that both the var expression and function declaration will be promoted to the top of the scope.

The Code is as follows:


Bar ();
Var bar = function (){};
Var someValue = 42;
Test ();
Function test (data ){
If (false ){
Goo = 1;
} Else {
Var goo = 2;
}
For (var I = 0; I <100; I ++ ){
Var e = data [I];
}
}

Before the above Code is run, the declaration of var expression and function test will be raised to the top, so the program will run normally and no error will be reported.

The Code is as follows:


// Var statements got moved here
Var bar, someValue; // default to 'undefined'
// The function declaration got moved up too
Function test (data ){
Var goo, I, e; // missing block scope moves these here
If (false ){
Goo = 1;
} Else {
Goo = 2;
}
For (I = 0; I <100; I ++ ){
E = data [I];
}
}
Bar (); // fails with a TypeError since bar is still 'undefined'
SomeValue = 42; // assignments are not affected by hoisting
Bar = function (){};
Test ();

Because Javascript does not have block-level scope, this will not only improve the var expression, but also make the if structure less intuitive.
In the above example, although it seems that if is operating on the global variable goo, in fact, the variable goo is upgraded, so it is modified by the local variable.
If you do not understand the escalation rules, you may think that the following code will throw a ReferenceError.

The Code is as follows:


// Check whether SomeImportantThing has been initialized
If (! SomeImportantThing ){
Var SomeImportantThing = {};
}

Of course, the above Code is correct, because before the code is running, the var expression has been promoted to the top.

The Code is as follows:


Var SomeImportantThing;
// Other code might initialize SomeImportantThing here, or not
// Make sure it's there
If (! SomeImportantThing ){
SomeImportantThing = {};
}

Here I would like to recommend @ nihtire van GE's blog "Understanding JavaScript (ii)", which provides a thorough explanation of the improvements.
Name Resolution Sequence

When you try to access a foo variable in a function scope, Javascript will look for it in the following order:

Whether var foo is defined in the current scope.
Whether the function parameters contain the foo variable.
Whether the function name is foo.
Jump to the outer definition field and start searching from the first part.
Namespace

One of the most common problems is naming conflicts, because Javascript has only one global scope. However, this problem can be solved through anonymous external functions.

The Code is as follows:


(Function (){
// A self contained "namespace"
Window. foo = function (){
// An exposed closure
};
}) (); // Execute the function immediately

In the preceding example, anonymous functions are considered expressions, so they are executed.

The Code is as follows:


(// Evaluate the function inside the parentheses
Function (){}
) // And return the function object
() // Call the result of the evaluation

Of course, we can also use other methods to call function expressions with different structures, but the same effect.

The Code is as follows:


// A few other styles for directly invoking
! Function (){}()
+ Function (){}()
(Function (){}());
// And so on...

Summary

We recommend that you use anonymous external functions to encapsulate code into a space. This not only resolves namespace conflicts, but also facilitates program modularization.
In addition, using global variables is not a good habit, which will lead to a high cost of maintenance and prone to errors.

Namespaces of the same type, functions, variables, templates, and so on all belong to the entity ).
The main commonality of an object is that it can have a name. (A tag can also have a name, but it is not an entity .)
The namespace scope is a general term in the scope, and is tied with block scope, Class scope, function prototype scope, and function scope (only valid for tags. The name declared in the namespace is in the namespace scope. The global name is considered to be in the implied global namespace scope.

The namespace does act as a scope. However, it is different from a simple scope. You can declare the same namespace multiple times, but the content in it cannot be redefined, they will eventually combine a namespace, like std, with macro definitions everywhere.

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.