Structuring JavaScript libraries: namespaces
When you write a JavaScript library, it is important to respect some rules if you want that the library is widely adopted.
The first rule is to avoid conflicts with other JavaScript. This is called leaving the smallest footprint. That means that global variables and functions should be avoided, because another library could accidentally use the same name. The best way is to define a single variable which contains all your code like this:
var MyNamespace = {
myGlobalVariable:23,
myFunction:function(x){
return x * x + this.myGlobalVariable;
}
};
You should only choose a unique "MyNamespace" that nobody else will happen to use. And if a conflict happens, you only have to change a single name on one place to resolve it.
Then you call your function like this:
var y = MyNamespace.myFunction(4);
There is even a way to leave no footprint at all by hiding your code into an anonymous function:
(function() {
var tDays=['Monday','Tuesday','Wednesday'];
for (var i=0; i<tDays.length; i++)
alert(tDays[i]);
})();
The drawback is that you can not reference that code from outside.
The second important rule is to write a documentation, and I will detail it in another post.
The first rule is to avoid conflicts with other JavaScript. This is called leaving the smallest footprint. That means that global variables and functions should be avoided, because another library could accidentally use the same name. The best way is to define a single variable which contains all your code like this:
var MyNamespace = {
myGlobalVariable:23,
myFunction:function(x){
return x * x + this.myGlobalVariable;
}
};
You should only choose a unique "MyNamespace" that nobody else will happen to use. And if a conflict happens, you only have to change a single name on one place to resolve it.
Then you call your function like this:
var y = MyNamespace.myFunction(4);
There is even a way to leave no footprint at all by hiding your code into an anonymous function:
(function() {
var tDays=['Monday','Tuesday','Wednesday'];
for (var i=0; i<tDays.length; i++)
alert(tDays[i]);
})();
The drawback is that you can not reference that code from outside.
The second important rule is to write a documentation, and I will detail it in another post.
Labels: JavaScript, Methodology

0 Comments:
Post a Comment
<$I18N$LinksToThisPost>:
Create a Link
<< Home