JavaScript advanced series-scope and namespace

Source: Internet
Author: User
Although JavaScript supports a pair of code segments created by curly brackets, it does not support block-level scopes, but only supports function scopes.
  • Implicit global variables

  • Local variable

  • Variable declaration elevation (Hoisting)

  • Name Resolution Sequence

  • Namespace

  • Conclusion

Although JavaScript supports a pair of code segments created by curly brackets, it does not support block-level scopes, but only supports function scopes.

Function test () {// a scope for (var I = 0; I <10; I ++) {// not a scope // count} console. log (I); // 10}

Note: If the left brackets and return of the return object are not in one row, an error occurs.

(Note: if it is not in the value assignment statement, but in the return expression or function parameter, {...} Will be parsed as a code segment, rather than as the literal syntax of the object. If Automatic semi-colon insertion is taken into account, this may cause some imperceptible errors .)

// Translator's note: The following output outputs undefinedfunction add (a, B) {return a + B;} console. log (add (1, 2 ));

JavaScript does not have an explicit namespace definition, which means that all objects are defined under a globally shared namespace.

Every time a variable is referenced, JavaScript will traverse the entire scope up until the variable is found. If the global scope is reached but the variable is not found, a ReferenceError error is thrown.

Implicit global variables

// Script Afoo = '42'; // script Bvar foo = '42'

The above two scripts have different effects. Script A defines the variable foo in the global scope, while script B defines the variable foo in the current scope.

Again, the effect is completely different. If you do not declare a variable using var, implicit global variables will be generated.

// Global scope var foo = 42; function test () {// partial scope foo = 21;} test (); foo; // 21

If you do not use the var keyword in the test function to declare the foo variable, it will overwrite the external variable with the same name. This does not seem to be a big problem at first, but when there are thousands of lines of code, it will be difficult to trace bugs if you do not use var to declare variables.

// Global scope var items = [/* array */]; for (var I = 0; I <10; I ++) {subLoop ();} function subLoop () {// subLoop function scope for (I = 0; I <10; I ++) {// The variable is not declared using var // work }}

The External Loop ends when subLoop is called for the first time, because subLoop overwrites the global variable I. Using var in the second for loop can avoid this error. When declaring a variable, do not omit the var keyword unless this is the expected behavior that affects the external scope.

Local variable

In JavaScript, local variables can only be declared in two ways. One is used as a function parameter, and the other is declared using the var keyword.

// Global variable var foo = 1; var bar = 2; var I = 2; function test (I) {// local scope I = 5 in function test; var foo = 3; bar = 4;} test (10 );

Foo and I are local variables in the test function, and the value of bar will overwrite the variables with the same name in the global scope.

Variable declaration elevation (Hoisting)

JavaScript promotes variable declaration. This means that both the var expression and function declaration will be promoted to the top of the current scope.

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];    }}

The above code will be converted before running. JavaScript will promote the var expression and function declaration to the top of the current scope.

// Var expression is moved here var bar, someValue; // The default value is 'undefined' // The function declaration will also increase function test (data) {var goo, I, e; // No block-level scope. These variables are moved to the top of the function if (false) {goo = 1;} else {goo = 2;} for (I = 0; I <100; I ++) {e = data [I] ;}} bar (); // error: TypeError, because bar is still 'undefined' someValue = 42; // The Value assignment statement will not be affected by the hoisting rule bar = function () {}; test ();

Without block-level scope, the var expression is not only moved from inside the loop to the outside, but also makes some if expressions more difficult to understand.

In the original code, the if expression seems to have modified the global variable goo. In fact, after the upgrade rule is applied, it is modifying the local variable.

If there is no hoisting knowledge, the following code seems to throw an exception ReferenceError.

// Check whether SomeImportantThing has been initialized if (! SomeImportantThing) {var SomeImportantThing = {};}

In fact, the above Code runs normally, because the var expression will be promoted to the top of the global scope.

Var SomeImportantThing; // some other code may initialize SomeImportantThing, or may not // check whether it has been initialized if (! SomeImportantThing) {SomeImportantThing = {};}

Note: there is an article about hoisting on the Nettuts + website. The code is enlightening.

// Note: A piece of code from Nettuts + vividly describes the variable declaration escalation rule var myvar = 'myvalue' in JavaScript; (function () {alert (myvar ); // undefined var myvar = 'local value ';})();

Name Resolution Sequence


All scopes in JavaScript, including global scopes, have a special name. this points to the current object. The function scope also has the default variable arguments, which contains the parameters passed to the function. For example, when accessing the foo variable in the function, JavaScript will look for it in the following order:

  1. Whether var foo is defined in the current scope.

  2. Whether the function form parameter uses the foo name.

  3. Whether the function itself is foo.

  4. Go back to the upper-level scope and start from #1 again.

Namespace

Naming conflicts are common errors caused by only one global scope. In JavaScript, this can be easily solved through the anonymous wrapper.

(Note: The Custom arguments parameter will prevent native arguments object creation .)

(Function () {// function to create a namespace window. foo = function () {// a function that is made public to the outside, and a closure is created} ;}) (); // immediately execute this anonymous function

Anonymous functions are considered expressions. Therefore, they are first executed to make them available.

(// The function in parentheses is first executed function () {}) // and returns the function object () // call the preceding execution result, that is, the function object.

There are some other methods that call function expressions. For example, the syntax of the two methods below is different, but the effect is the same.

// The other two methods + function () {} (); (function (){}());

Conclusion


We recommend that you use the anonymous wrapper (Translator's note: Self-executed anonymous functions) to create a namespace. This not only prevents naming conflicts, but also facilitates program modularization.

In addition, using global variables is considered a bad habit. Such code is prone to errors and the maintenance cost is high.

The above is the content of the JavaScript advanced series-scope and namespace. For more information, see PHP Chinese website (www.php1.cn )!

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.