JavaScript.The.Good.Parts reading notes (ii) Scope & closure & techniques for mitigating global space pollution _javascript

Source: Internet
Author: User
Tags anonymous closure
such as code blocks
Copy Code code as follows:

if (true) {
int i = 100;
}
print (i); Error, variable i no declaration

As shown in the example above, a function outside of a block of code cannot access the I variable.
But in JavaScript, things are completely different.
Copy Code code as follows:

if (true) {
var i = 100;
}
alert (i); Pop-up box and display 100

Many modern languages recommend declaring variables as late as possible, but this is one of the worst suggestions in JavaScript. Because of the lack of block-level scopes, it is a good idea to declare all the variables that might be used in a function at the top of the function body.


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


var bankAccount = function () {
var value = 0;
return {
Deposit:function (inc) {
Value + + inc;
},
Getvalue:function () {
return value;
}
}
}


var myaccount = BankAccount (); Open a new bank account
Myaccount.deposit (1000); Save 1000 bucks in there.
Alert (Myaccount.getvalue ()); Should alert (1000);


Value because it cannot be directly manipulated outside of the BankAccount function, it must be manipulated by the BankAccount function to the object that he returns, thus realizing private fields in C # and Java.

Mitigation of global variable pollution global space: Using the scope of functions, we write JS Library can reduce the conflict with other libraries.
Copy Code code as follows:

(function () {
var hello = ' Hello world ';
})();
alert (hello); Error:hello no exist.

The syntax here is a little weird, the main idea is to define an anonymous method and execute it immediately. Because the litertal of the function begins to be interpreted as a functional definition, a pair of parentheses is added to enclose it, and then a pair of parentheses is used to call this function. External alert access does not have a hello defined inside the function.


Trap one: the pitfalls of Var

The example of "mitigating global space pollution by global variables" is changed to
Copy Code code as follows:

(function () {
Hello = ' Hello world '; Remove Var
})();
alert (hello); Alert (' Hello world. ');

When the variable hello is not explicitly declared with Var, hello becomes a global variable!!

While using this feature, we can provide an external interface, but it is not recommended.
Copy Code code as follows:

(function () {
var hello = ' Hello world ';
SayHello = function () {//It is not recommended to provide an interface in this way, it does not look obvious.
alert (hello);
}
})();
SayHello ();

can be improved to
Copy Code code as follows:

(function (window) {
var hello = ' Hello world ';
window.$ = {
Sayhello:function () {
alert (hello);
}
};
}) (window);
$.sayhello (); Looks like jquery, so cool.

Or

Copy Code code as follows:

var obj = (function () {
var hello = ' Hello world ';
return {
Sayhello:function () {
alert (hello);
}
};
})();
Obj.sayhello ();


Trap two: The trap of closure

Copy Code code as follows:

(function () {//functions A
var arr = [];
var i = 0;
var J;
for (; i < 3; i++) {
Arr.push (function () {//functions B
Alert (i * 10);
});
}


For (j in Arr) {
ARR[J] ();
}
})();


It is thought that the function array arr the function after the execution, will pop 0,10,20, but the result is not so. The result is a pop-up 30,30,30.
Function B accesses not the value of I at that time, but the direct access to the variable I (for all the most recent values).
The reason is that function B is the internal function of function A, the variable i is visible to function B, and function B gets the most recent value from I at a time.

This time, the change is:
Copy Code code as follows:

(function () {//functions A
var arr = [];
var i = 0;
var J;
for (; i < 3; i++) {
Arr.push ((function (anotheri) {//function M
return function () {//functions B
Alert (Anotheri * 10);
}
}) (i)); Here is (function B (anotheri) {}) (i)
}


For (j in Arr) {
ARR[J] ();
}
})();

After this execution, finally popped up 0,10,20. This is why.

Function B accesses the Anotheri (the value of I at that time) rather than directly accessing the variable i.
Each time before Arr.push, a new anonymous function m is defined. In this example, 3 anonymous function m0,m1,m2 are defined, and each time they are called, their anotheri get the value of the current I. Each M function returns a B function after execution. B0 in M0, B1 in M1, B2 in M2. B0 can only access M0 's Anotheri (0), while B0 cannot access M1 Anotheri, 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.