Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Just how reserved are the words private and public in JavaScript

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?

like image 327
Oscar Godson Avatar asked Jun 23 '11 18:06

Oscar Godson


3 Answers

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.

like image 119
hughes Avatar answered Oct 19 '22 00:10

hughes


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".

like image 9
Marc B Avatar answered Oct 19 '22 01:10

Marc B


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();
like image 2
Trendfischer Avatar answered Oct 19 '22 01:10

Trendfischer