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

How to implement block scope in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:31:001005browse

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.
Statement:
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