One of my interview questions is to ask how to avoid page reference JS, function, variable repetition, conflict.
On the big side, JavaScript should be introduced in modular development, in line with the AMD specification;
From the small aspect, it is probably the scope of the limited variables and functions, which also involves a little thunderclap piercing concept of closure.
As we all know, JavaScript has no classes, only functions. In fact, its function is similar to the class, functions can be defined inside the function. For. NET, this is not supported until the recent c#7.
So, we can define functions and variables in a function so that it is isolated from the outside:
<head ; </head ; <body ; </body ; </html ; <script ; (function () { function f1 () {}; var v1; ....}) (); </script ;
Writing in a page like this is equivalent to:
<html><head></head><body></body></html><script> function f1(){}; var v1; ....</script>
But encapsulation is a lot better, avoid the latter of this tile straightforward, the methods and variables completely exposed to the outside world. And (function(){})(); This approach can be applied to sub-functions, and even to all functions, layers of encapsulation, no end. And there is a closure attribute that does not have to worry about global binding access to the inner layer of the function:
(function(){ function f1(){} function f2(){} $("#btn1").click(function(){ f1(); f2(); });}
Improve the encapsulation of code in JavaScript