Home > Web Front-end > JS Tutorial > JavaScript.The.Good.Parts Reading Notes (2) Scope & Closure & Mitigating Global Space Pollution_Javascript Skills

JavaScript.The.Good.Parts Reading Notes (2) Scope & Closure & Mitigating Global Space Pollution_Javascript Skills

WBOY
Release: 2016-05-16 18:16:23
Original
1206 people have browsed it

For example, code block

Copy code The code is as follows:

if (true) {
int i = 100;
}
print(i); //Error, variable i is not declared

As shown in the above example, functions outside the code block cannot access the i variable .
But in javaScript, the situation is completely different.
Copy code The code is as follows:

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

Many modern languages ​​recommend declaring variables as late as possible, but in Javascript this is the worst suggestions. 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 block-level scope is missing, the scope of the function still exists.
One advantage of this kind of scope is that inner functions can access the parameters and variables of the outer function in which they are defined (except this and argument).
Using this feature, you can design the code like this.
Copy code The code is 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); //Deposit 1000 yuan
alert(myAccount.getValue()); //should alert(1000);


value Because it is in the bankAccount function, it cannot be directly operated by the outside world, and must be passed through bankAccount The function gives the object it returns to perform operations, and in this way the private fields in C# and Java are implemented.

Reduce global variables from polluting the global space: Using the scope of functions, we can reduce conflicts with other libraries when writing js libraries.
Copy code The code is as follows:

(function () {
var hello = ' Hello World.';
})();
alert(hello); //error: hello no exist.

The syntax here is a bit weird, the main idea is to define a Anonymous method and executed immediately. Since the litertal at the beginning of function will be interpreted as a function definition, a pair of parentheses are added to surround it, and then a pair of parentheses are used to indicate that the function is called. External alert cannot access hello defined inside the function.


Trap 1: Trap of var

The example of "slowing down global variables from polluting global space" was changed to
Copy code The code is 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! !

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

(function () {
var hello = ' Hello World.';
sayHello = function () { //It is not recommended to provide the interface in this way, it seems very unclear
alert(hello);
}
})( ;

(function (window) {
var hello = 'Hello World.';
window.$ = {
sayHello: function () { alert(hello ); } }; })(window); $.sayHello(); //Looks as cool as jQuery
or





Copy code


The code is as follows:

var obj = (function () {
var hello = 'Hello World.';
return {
sayHello: function () { alert(hello); } }; })(); obj.sayHello();


트랩 2: 클로저 트랩

코드 복사 코드는 다음과 같습니다

(function () { //함수 a
var arr = [];
  var i = 0;
var j;
for ( ; i < 3; i ) {
arr.push(function () { //함수 b
alert(i * 10);
})
}


for (j in arr ) {
arr[j]();
}
})();


함수 배열 arr의 각 함수가 실행된 후 0, 10,20이 팝업되지만 그렇지 않은 것으로 나타났습니다. 결과는 30,30,30이 나타납니다.
함수 b는 i의 현재 값에 액세스하지 않고 변수 i에 직접 액세스합니다(항상 i의 최신 값을 가져오는 데 사용됨).
이유는 함수 b는 함수 a의 내부 함수이고 변수 i는 함수 b에 표시되며 함수 b는 매번 i에서 최신 값을 가져오기 때문입니다.

이번으로 변경되었습니다:
코드 복사 코드는 다음과 같습니다.

( function () { //function a
var arr = [];
var i = 0;
  var j;
for ( ; i < 3; i ) {
arr.push((function (anotherI) { //함수 m
return function () { //함수 b
alert(anotherI * 10);
}
})(i) ); // 여기 있습니다 (function b(anotherI) {})(i)
}


for (j in arr) {
arr[j](); >}
})();

이 실행 후 마침내 0,10,20이 나타났습니다. 왜 이런가요?

함수 b는 변수 i에 직접 접근하는 대신 anotherI(당시 i의 값)에 접근한다.
arr.push 이전마다 새로운 익명 함수 m이 정의됩니다. 이 예에서는 세 개의 익명 함수 m0, m1 및 m2가 호출될 때마다 otherI가 현재 i의 값을 가져옵니다. 각 m 함수는 실행 후 b 함수를 반환합니다. b0은 m0에 있고, b1은 m1에 있고, b2는 m2에 있습니다. b0는 m0(0)의 다른 I에만 액세스할 수 있지만 m0과 m1은 서로 다른 함수이기 때문에 b0은 m1의 다른 I에 액세스할 수 없습니다.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template