JavaScript Learning Notes function chapter (vi): Scope and Namespace _ basics

Source: Internet
Author: User
Tags anonymous function prototype

In the previous introduction, we already know that Javascript has no block-level effect, only function-level scopes.

Copy Code code as follows:

function test () {//a scope
for (var i = 0; i < i++) {//Not a scope
Count
}
Console.log (i); 10
}

There is also no namespace displayed in Javascript, which means that everything is defined in the global scope. Each time a variable is referenced, Javascript iterates up the entire global scope until the variable is found. If the variable is still not found after traversing the entire global scope, a referenceerror error is thrown.

Please enter a picture description

An implicit global variable

Copy Code code as follows:

Script A
foo = ' 42 ';
Script B
var foo = ' 42 '

The two examples above produce a different effect. The first one will define the variable Foo in the global scope, and the second defines the variable foo in the current scope.
It is important to note that if you do not use the keyword VAR, you will have an unexpected impact.

Copy Code code as follows:

Global scope
var foo = 42;
function Test () {
Local scope
foo = 21;
}
Test ();
Foo 21st

Because Var is not used in function test to define variable foo, global variable foo outside the function is overwritten. Although it may not seem like a big problem, if there are thousands of lines of code, it will be a bug that is untraceable.

Copy Code code as follows:

Global scope
var items = [/* some list];
for (var i = 0; i < i++) {
Subloop ();
}
function Subloop () {
Scope of Subloop
for (i = 0; i < i++) {//missing VAR statement
Do amazing stuff!
}
}

In the example above, the outer loop will stop at the first time because the variable i inside the Subloop function will overwrite the external global variable I. We just need to add a var inside the function to avoid this error, so we must not forget to add the keyword var when we define the variable. Unless we really want to have an impact on external global variables.

Local variables

Local variables in Javascript can only be generated in two ways, one through the keyword Var, and one as the function's formal parameters.

Copy Code code 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);

At this point, the variables inside the function test I and Foo are local variables, and bar overrides the external global variable bar.

Promotion (hoisting)

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

Copy Code code 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 < i++) {
var e = data[i];
}
}

Before the code is run, the Var expression and the declaration of the function test are raised to the top, so the program will run correctly without an error.

Copy Code code 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
if (false) {
Goo = 1;
} else {
Goo = 2;
}
for (i = 0; i < 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 ();

Since Javascript does not have block-level scopes, this will not only elevate the Var expression, but also make the if structure less intuitive.
In the example above, although it appears that the if is operating on the global variable goo, in fact, because the variable goo is promoted, the local variable is modified.
If you do not have an understanding of the promotion rules, you may think that the following code will throw a referenceerror error.

Copy Code code as follows:

Check whether Someimportantthing has been initialized
if (! someimportantthing) {
var someimportantthing = {};
}

Of course the code above is not wrong because the VAR expression has been elevated to the top before the code runs.

Copy Code code as follows:

var someimportantthing;
Other code might initialize someimportantthing, or not
Make sure it ' s there
if (! someimportantthing) {
someimportantthing = {};
}

Here to recommend the next @nightire the Bowen "understanding of JavaScript (ii)", inside the explanation of Ascension is very thorough.
Name resolution Order

When you try to access an Foo variable within a function scope, Javascript will look in the following order:

Is there a definition of Var foo in the current scope.
Whether there is an Foo variable in the function parameter.
Whether the name of the function itself is foo.
Jump to the outer definition field and start looking at the first part.
Name space

One of the most common problems is naming conflicts, because Javascript has only one global scope. But this problem can be solved by an anonymous external function.

Copy Code code as follows:

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

The anonymous functions in the example above are considered expressions, so they are executed.

Copy Code code 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 call function expressions in other ways, different structures, but the same effect.

Copy Code code as follows:

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

Summarize

It is recommended that you use anonymous external functions to encapsulate code in space, not only to resolve namespace conflicts, but also to facilitate the modularity of the program.
In addition, the use of global variables is not a good habit, which will result in costly maintenance costs and error-prone.

Namespaces are owned by entities (entity) with types, functions, variables, templates, and so on.
The main commonality of entities is that they can have names. (in addition, a label can have a name, but it is not an entity.) )
The namespace scope is a generic term in the scope and is tied to block scope, class scope, function prototype scope, function scope (valid only for labels). The name declared within the namespace is in the namespace scope. Global names are considered to be in the implied global namespace scope.

The

Namespace action is indeed a scope, but unlike a simple scope, you can declare the same namespace multiple times, but the contents cannot be redefined, and they will eventually synthesize a namespace, like STD, where macros are defined everywhere

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.