How to Work with JavaScript’s Private Properties and Methods to Program with HTML

Many web developers are under the impression that JavaScript doesn’t provide private properties or methods. This isn’t the case. It’s true that JavaScript does lack any specific keyword that designates a particular property or method as private, but the fact remains that it can create and manage private members.

Private members are always created as part of an object’s constructor. You can either create properties as a parameter for the constructor or create it within the constructor itself. Private methods are nested within the constructor. The following code shows both private properties and a private method.

// param is private.
function TestObject(param)
{
  // ThisString is private.
  ThisString = "abc";
 
  // ChangeString is private.
  function ChangeString(input)
  {
   return input.toUpperCase();
  }
}

If you now create a function to test this object, such as CreateObject() shown in the following code, you find that the application fails to produce the desired result. In fact, if you’re using an editor specifically designed for working with JavaScript, you’ll find that param, ThisString, and ChangeString() don’t even show up as possible choices. The members are inaccessible.

function CreateObject()
{
  var DoTest = new TestObject("def");
  document.getElementById("Result").innerHTML =
   DoTest.ChangeString("def");
}

The private members of TestObject are also inaccessible to any public methods that you create. Of course, this presents a problem because the object now has private data that’s seemingly inaccessible to anything but the constructor. JavaScript has a third level of visibility called privileged. Here’s a privileged method for TestObject:

// MeldData is privileged.
this.MeldData = function()
{
  return ChangeString(ThisString + param);
}

This function is also defined within the constructor. However, in this case, it’s assigned to a public variable, MeldData, that acts as a true method. Your editor will display it as a method when you access it. You can pass it data like any other method.

However, this method is privileged and has full access to the private data in TestObject. If you change CreateObject() so it looks like the following example, the application now produces the desired output:

function CreateObject()
{
  var DoTest = new TestObject("def");
 
  // This code won't work.
  //document.getElementById("Result").innerHTML =
  //  DoTest.ChangeString("def");
 
  // This code will.
  document.getElementById("Result").innerHTML =
   DoTest.MeldData();
}
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.