Students who have used Java and C# are very familiar with namespaces. In a complex system, there will be many functions and objects, provided by the language and predefined by the architecture. With so many functions and objects, due to programming specifications If you ask for a name with practical meaning, it will inevitably lead to incorrect calls due to the same name. But with the namespace, the trouble is gone. Not only can functions and objects be classified and organized, but also isolation can be formed to solve the problem of duplicate names.
Using JavaScript is not so comfortable. Javascript only has function scope. Blocks and Shenma files are all considered to be a namespace. Sometimes errors caused by some duplicate names are baffling and difficult to understand. Debugging and solving.
A simple example
Since JavaScript does not have file scope, different functions are scattered in different files, or even written by different people, and the probability of duplicate names is greatly increased. Is it enough to be careful enough? Not necessarily. There are also some unexpected situations. For example, inheritance is often used, so I wrote a function name extend that has never appeared before. Unexpectedly, the extend function was added to EcmaScript5, and the necessity of namespaces was reflected.
JavaScript has function scope. You can use this to write custom functions into a function body, so that the variables, objects, and functions in the function are isolated from the outside just like they are in a namespace.
This is possible, but there are problems. The biggest problem is that the calling method is complicated and ugly! The object must be instantiated every time it is called, and then its methods must be called. Simply modify the code to achieve automatic instantiation.
Copy code