Home >Web Front-end >JS Tutorial >Manage the use of namespaces to avoid conflicts in js and avoid the proliferation of global variables_javascript skills

Manage the use of namespaces to avoid conflicts in js and avoid the proliferation of global variables_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 16:44:311220browse

In order to avoid overwriting and conflicts between variables, a namespace can be generated. The namespace is a special prefix, which is implemented through the { } object in js.

In different anonymous functions, declare a different namespace according to the function. The attributes of the GLOBAL object in each anonymous function are not directly hung on GLOBAL, but are hung under the namespace of the sub-anonymous function. , such as:

Copy code The code is as follows:






If the program in the same anonymous function is very complex and has many variable names, the namespace can be further expanded to generate a secondary namespace:
Copy code The code is as follows:




Since generating namespace is a very common function, the function of generating namespace can be further defined as a function , convenient to call, as follows:
Copy code The code is as follows:



The specific operation of calling the namespace:
Copy code The code is as follows: