Every day we have more JavaScript code and we need to organize it. One of the
most common problems of JavaScript is its total lack of structure and isolation.
Many times we end up with a lot of variables defined globally. To avoid
this type of problematic we can define Namespaces that isolate us some elements of
others. Let's see a simple example.
/ *
var MIESPACIOA = MIESPACIOA || {};
MIESPACIOA.person = {name: "pedro", age: 20};
console.log (MIESPACIOA.personname.name);
var MIESPACIOB = MIESPACIOB || {};
MIESPACIOB.person = {name: "Maria", age: 15};
console.log (MIESPACIOB.personname.);
We have just created two javascript namespace in each of which we have stored
an object. That yes both objects have the same name "person" although they store data
different. If this we had done at a global level the program would not work. Without
however when storing it in "namespaces" everything will work correctly.
Example of Javascript NameSpace
If we print the data by the console the result will be:
Working with Namespaces is critical in the current JavaScript applications. Many
Java developers are more comfortable with a Namespace syntax plus
close to their language. For this we can design the following function that will generate the
Namespaces in a simpler way.
var MIAPPLICACION = {};
MIAPPLICACION.namespace = function (spaces) {
var listSpaces = spaces. split ('.');
var spacePad = this;
for (var i = 0; i <listSpaces.length; i ++) {
var newSpace = listSpaces [i];
Example of Javascript NameSpace
console.log (newSpace);
if (! SpaceFather [nuevoEspacio]) {
spaceFather [nuevoEspacio] = {};
}
spaceFather = spaceFather [nuevoEspacio];
}
};
// creation namespace
MIAPPLICACION.namespace ("com.arquitecturajava");
console.log (MIAPPLICACION);
The result that the console will print will be :
As we can see we have generated the structure of Namespaces that we wanted.
Other related articles: Javascript Templates, JQuery Context, Javascript JPerf [19659026].
from Nettech Post http://bit.ly/2FijFbL
No hay comentarios:
Publicar un comentario