JavaScript. The. Good. Parts Reading Notes (2) Scope closure reduces global space pollution

Source: Internet
Author: User

Such as code block Copy codeThe Code is as follows: if (true ){
Int I = 100;
}
Print (I); // error, variable I is not declared

As shown in the preceding example, functions outside the code block cannot access the I variable.
But in javaScript, the situation is completely different.Copy codeThe Code is as follows: if (true ){
Var I = 100;
}
Alert (I); // The displayed dialog box is 100.

Many modern languages recommend declaring variables as late as possible, but this is the worst advice in Javascript. Due to the lack of block-level scope, it is best to declare all variables that may be used in the function at the top of the function body.

Closure features:
Although the block-level scope is missing, the function scope still exists.
One benefit of this scope is that internal functions can access the parameters and variables (except this and argument) that define their external functions ).
With this feature, you can design the code in this way.Copy codeThe Code is as follows:

Var bankAccount = function (){
Var value = 0;
Return {
Deposit: function (inc ){
Value + = inc;
},
GetValue: function (){
Return value;
}
}
}

Var myAccount = bankAccount (); // create a new bank account
MyAccount. deposit (1000); // store 1000 pieces
Alert (myAccount. getValue (); // shocould alert (1000 );

Value in the function bankAccount, external operations cannot be performed on it directly. Therefore, you must use the function of bankAccount to operate on the objects returned by it, in this way, the private fields in C # and java are implemented.

Slowing down global variable pollution global space: using the function scope, we can reduce conflicts with other libraries when writing JavaScript libraries.Copy codeThe Code is as follows: (function (){
Var hello = 'Hello World .';
})();
Alert (hello); // error: hello no exist.

The syntax here is a bit strange. The main idea is to define an anonymous method and execute it immediately. Since the litertal at the beginning of the function will be interpreted as the function definition, a pair of brackets are added here to enclose it, and then a pair of parentheses are used to call this function. External alert cannot access the hello defined in the function.

Trap 1: var traps

The example of "slowing down global variables and polluting global space" is changedCopy codeThe Code is as follows: (function (){
Hello = 'Hello World. '; // remove var
})();
Alert (hello); // alert ('Hello World .');

When the variable hello is not explicitly declared using var, hello becomes a global variable !!

Although we can use this feature to provide an external interface, we do not recommend this.Copy codeThe Code is as follows: (function (){
Var hello = 'Hello World .';
SayHello = function () {// This method is not recommended to provide the interface, and it does not seem obvious.
Alert (hello );
}
})();
SayHello ();

Can be improvedCopy codeThe Code is as follows: (function (window ){
Var hello = 'Hello World .';
Window. $ = {
SayHello: function (){
Alert (hello );
}
};
}) (Window );
$. SayHello (); // looks as cool as jQuery

Or

Copy codeThe Code is as follows: var obj = (function (){
Var hello = 'Hello World .';
Return {
SayHello: function (){
Alert (hello );
}
};
})();
Obj. sayHello ();

Trap 2: Closure traps

Copy codeThe Code is as follows: (function () {// function
Var arr = [];
Var I = 0;
Var j;
For (; I <3; I ++ ){
Arr. push (function () {// function B
Alert (I * 10 );
});
}

For (j in arr ){
Arr [j] ();
}
})();

After executing the functions in the arr array, the values 0, 10, and 20 are displayed, but the result is not the same. The result is 30, 30, and 30.
Function B does not access the I value at the time, but directly accesses variable I (used to obtain the latest I value ).
The reason is that function B is an internal function of function a. Variable I is visible to function B, and function B obtains the latest value from function I every time.

This time changed:Copy codeThe Code is as follows: (function () {// function
Var arr = [];
Var I = 0;
Var j;
For (; I <3; I ++ ){
Arr. push (function (anotherI) {// function m
Return function () {// function B
Alert (anotherI * 10 );
}
}) (I); // here is (function B (anotherI) {}) (I)
}

For (j in arr ){
Arr [j] ();
}
})();

After this execution, the values 0, 10, and 20 are displayed. Why.

Function B accesses anotherI instead of directly accessing variable I.
Each time before arr. push, a new anonymous function m is defined. This example defines three anonymous functions: m0, m1, and m2. Each time they are called, their anotherI gets the current I value. After each m function is executed, a B function is returned. B0 is in m0, b1 is in m1, and b2 is in m2. B0 can only access anotherI (0) of m0, while b0 cannot access anotherI of m1, because m0 and m1 are different functions.

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.