Yet Another Method to declare private methods and variables in Javascript

  • : Function split() is deprecated in /hsphere/local/home/guruj/guruj.net/modules/filter/filter.module on line 1200.
  • : Function split() is deprecated in /hsphere/local/home/guruj/guruj.net/modules/filter/filter.module on line 1200.
  • : Function split() is deprecated in /hsphere/local/home/guruj/guruj.net/modules/filter/filter.module on line 1200.
  • : Function split() is deprecated in /hsphere/local/home/guruj/guruj.net/modules/filter/filter.module on line 1200.

A number of people have described methods for private variables and methods within JavaScript.

In that spirit, this is another possible template. The main difference between this version and most others is that it uses the concise JSON notation for variable and method declarations.


File.Writer = File.Writer || function (filename, append, binaryMode) {
  //:: private variables
  with({
    binaryMode: binaryMode || false,
    handle: (function () { 
      if (binaryMode) { return new IO.FileOutputStream(filename, append) }
        else { return new IO.FileWriter(filename, append); }
    })()
  }) {
    //:: private methods
    with({

    }) {
      //:: public methods and functions
      var construct = {
        write: function (data) {
          handle.write(data, 0, (data.length || 32767));
        },
        close: function () { 
          handle.close(); 
        }
      }
    }
 
    //:: object initialiser 
    
  } return construct;
}

The usage of this object is then simply:


// returns a new instance of the File.Writer class
var x = File.Writer("\temp\test.txt", true);
x.handle();   // ERROR! returns "cannot find function"
x.write("Hello world");
x.close();

The chief drawback is that because JSON notation can only return Objects and not Functions, .prototype-style inheritance isn't possible. But it's a neat way to handle objects, and particularly singleton instances.