Each time I build a JS library I have this sort of concept:
(function(window,undefined){
var LibName = function(){
var privateAPI = {
method: function(){}
};
var publicAPI = {
publicMethod: function(){}
};
return publicAPI;
}
window.LibName = LibName;
})();
But i've always longed for just doing:
(function(window,undefined){
var LibName = function(){
var private = {
method: function(){}
};
var public = {
publicMethod: function(){}
};
return public;
}
window.LibName = LibName;
})();
But I've never done that because those are reserved words. Just how reserved are they? Will a browser fail? In my testing, everything seems to work, but am I missing something?
Always assume that using reserved words improperly will cause the application to fail.
Words like public
and private
are future reserved words, so even if they work now the might not in the future.
https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
and
http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf for the official specification.
They're listed in 7.6.1.2 as "reserved for future use".
I would not recommend to use private and public. But you'll get an error only by using strict mode with "use strict": https://developer.mozilla.org/en/JavaScript/Strict_mode
If you want to be sure, it will work in the future, you would have to use parentheses:
this["private"] = {
method: function() {}
}
I prefer to shorten the var to "pub" and "priv". So I use a pattern like this:
namespace.decorator = function (pub, priv) {
pub = pub || {};
priv = priv || {};
//namespace.decoratorToExtend(pub, priv);
pub.method = function() {alert(pub.prop)};
return pub;
}
var instance = namespace.decorator({prop:'hello world'});
instance.method();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With