Namespace-Friendly JavaScript APIs
JavaScript has no support for packages or modules, so namespace conflicts are rampant. In particular, as JavaScript obfuscators become prevalent, a lot of JavaScript libraries have started to look like this (an actual snippet of the Google Maps API JavaScript):
function Cb(a){a.remove();Gb(ab,a)}
Given these obfuscators choose the shortest names possible to make the size of the JavaScript as small as possible, the likelihood of a name collision when multiple APIs are included in a page is almost 100% -- after all, there are only 26 letters in the alphabet.
When you make a JavaScript library, you can make it play well with others by only exporting those symbols that are a part of your API using this simple recipe. First, concatenate all of your JavaScript source code, and surround it in a single, anonymous function:
(function() { var privateVariable = 3; function MyPublicClass() { } function MyPrivateClass() { } })();
This will prevent any of your symbols from being accessible to pages that include the API. Then, explicitly export the symbols that make up your API with this simple export function:
function exportSymbol(name, symbol) { window[name] = symbol; }
In the case of the API above, we would add this line to the end of our anonymous function:
(function() { var privateVariable = 3; function MyPublicClass() { } function MyPrivateClass() { } exportSymbol("MyPublicClass", MyPublicClass); })();
Now, MyPublicClass
will be accessible, but the other two symbols defined are "private" and will not interfere with the other libraries included by your API clients.
Comments
var myAPI = function()
{
function MyPrivateClass() {}
return {
"myPublicClass":function() {}
};
}();
function myAPI() {}
myAPI.MyPrivateClass = {
intX : 6,
setX : function (x) {
function addX() {
x += 1;
}
addX();
return x + myAPI.MyPrivateClass.intX;
}
}
alert(myAPI.MyPrivateClass.setX(6)); //alert "13"
Surrounding the entire thing in an anonymous function is also an easy thing to do in a post-processing stage with compilation/obfuscation, so you do not need to touch your code in practice (also very convenient).
Write a Comment