Javascript simply implements namespace effects
- 2020-03-30 02:14:58
- OfStack
Namespaces matter when we create a JavaScript library, where we can encapsulate the scattered JavaScript files (*.js) that make up the library without having to define global functions or classes. For example, the Person that appears several times in this section can be encapsulated as part of the library into an appropriate namespace:
Code 5-14:
var ns = com.anyjava;
var dirk = new ns.Person("Dirk");
dirk.eat();
The last thing I'm going to show you is that there's one thing to be aware of when using namespaces. When writing JavaScript libraries, in most cases the namespace declaration statement may also appear in multiple locations, a JavaScript file or in multiple JavaScript file, but the JavaScript language feature is the final statement variables will cover the front statement of the same name, this needs our attention to the problem of repeated statements, that is to say, every time statement namespace object, suggest to judge whether the object under the namespace already exists, as shown in Code 5-15:
Code 5-15:
if (typeof com.anyjava == "undefined") var com.anyjava = {};
This ensures that the "com.anyjava" object is declared only once.