Home > Web Front-end > JS Tutorial > How to implement block scope in JavaScript_javascript tips

How to implement block scope in JavaScript_javascript tips

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:31:00
Original
1037 people have browsed it

For example, the following code

Copy code The code is as follows:

{
var temp = "12";
}
alert(temp); //Output 12

If according to the usual programming experience, the alert function cannot access the temp variable because it In another block, but in JavaScript, there is no concept of block scope, so this syntax does not work for JS, but when we write JS programs, especially larger programs or libraries, in order To prevent naming conflicts, a mechanism for controlling variable scope is needed, so here is a more common way to implement the concept of block scope. The code is as follows:
Copy code The code is as follows:

(function() {
var temp = "123";
})();
alert(temp); //Output error

As in the above code, a function expression is defined and then called immediately. This form imitates the concept of block scope and protects the contents of the block. namespace, this method is very useful in some larger program libraries
(such as JQuery), and effectively avoids naming conflicts. In fact, JQuery uses this method to implement block scope.
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
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template