Home > Article > Web Front-end > Javascript namespace pattern code example
Namespace is created by creating a global object for a project or library, and then adding all functionality to that global variable. By reducing the number of global variables in the program, a single global variable is implemented, thereby not causing global pollution when there are a large number of functions, objects, and other variables, and also avoiding problems such as naming conflicts
However, in When adding attributes to a namespace in different files, you must first ensure that the namespace already exists, and at the same time do not cause any damage to the existing namespace. It can be achieved through non-destructive namespace functions:
The code is as follows:
var KUI = KUI || {}; KUI.utils = KUI.utils || {}; KUI.utils.namespace = function(ns){ var parts = ns.split("."), object = KUI, i, len; if(parts[0] === "KUI"){ parts = parts.slice(1); } for(i = 0, len = parts.length; i < len; i+=1){ if(!object[parts[i]]){ object[parts[i]] = {}; } object = object[parts[i]]; } return object; };
Usage:
The code is as follows:
KUI.utils.namespace("KUI.common"); KUI.utils.namespace("KUI.common.testing"); KUI.utils.namespace("KUI.modules.function.plugins"); KUI.utils.namespace("format");
Look at what KUI has after the above:
The code is as follows:
{ "utils": {}, "common": { "testing": {} }, "modules": { "function": { "plugins": {} } }, "format": {} }
Disadvantages of the namespace mode
1. Longer characters need to be entered, and more characters need to be entered. Long parsing time;
2. Dependence on a single global variable, that is, any code can modify the global instance, and other code will obtain the modified instance.
The above is the detailed content of Javascript namespace pattern code example. For more information, please follow other related articles on the PHP Chinese website!