Home  >  Article  >  Web Front-end  >  Javascript namespace pattern_javascript tips

Javascript namespace pattern_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:17:56908browse

However, 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. This can be achieved through non-destructive namespace functions:

Copy code 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:

Copy code 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 going through the above:

Copy code The code is as follows:

{
"utils": {},
"common": {
"testing": {}
},
"modules": {
"function": {
"plugins": {}
}
},
"format": {}
}

Disadvantages of the namespace pattern

1. Need to enter longer characters and require longer parsing time;
2. Dependence on a single global variable, that is, any code can modify the global instance, and other codes will get the modified Example.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn