JavaScript and Private Class Members

I was teaching an intermediate level JavaScript class last week and I used an example that many experienced JavaScript coders don’t know about, and that is how to create a JavaScript class with private data members. Consider this:
 
function Book(t,p)
{
  // public
  this.title = t;
  this.pages = p;
  this.toString = function()
    { return this.title + " # " + this.pages; };
}
 
function main()
{
  var b = new Book("Test Automation",123);
  WScript.Echo(b.toString());
  b.pages = 321;
  WScript.Echo(b.toString());
}
 
main();
 
The output is ‘Test Automation # 123’ followed by ‘Test Automation # 321’ as you would expect. Here I have a normal Book class in JavaScript where data members title and pages are public and so can be accessed and manipulated by the calling code in the main() function. Here’s how to make the data private:
 
function Book(t,p)
{
  // private
  var title = t;
  var pages = p;
 
  // public
  this.getTitle = function() { return title; };
  this.setTitle = function(t) { title = t; };
  this.getPages = function() { return pages; };
  this.setPages = function(p) { pages = p; };
  this.toString = function() { return title + " # " + pages; };
}
 
By using the "var" keyword instead of the "this" keyword, title and pages can no longer be accessed or manipulated directly so I code public functions to perform those operations. If now:
 
var b = new Book();
b.title = "Software Testing"; // ignored
b.pages = 111; // ignored
WScript.Echo(b.toString());
 
the output is ‘undefined # undefined’. However if:
 
var b = new Book();
b.setTitle("Software Development");
b.setPages(222);
WScript.Echo(b.toString());
 
the output is Software Development # 222′ as you’d expect.
This entry was posted in Software Test Automation. Bookmark the permalink.