Browse DevX
Sign up for e-mail newsletters from DevX


Encapsulate Your JavaScript: Keep Private Methods Private-5 : Page 5




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Build the Example
Open your favorite text editor, enter or download the code in Listing 1, and save the file as myObject.js:

This code looks slightly different than most JavaScript. Notice that all the code exists within the function definition—in other words, the member functions are nested within the myObject() function. The myObject() function is the constructor for objects of type myObject. Nothing new there. The next two lines declare two member variables, prop1 and prop2, and initialize them. Notice that the function omits the this keyword and uses the var keyword instead. Omitting the this keyword makes the variables private to the object. The var keyword makes the property local (each object instance gets its own copy of the variable). Calls to internal methods then assign the passed argument values to the properties (see the SideBar Cross-Browser Issues with the Sample Code).

The next part of the code is a list of method pointers defined with the this keyword. The method pointers make the methods public. Each method pointer points to a getter or setter method that lets you retrieve and set the values of the private data member values. In essence, they let the object control how the values change internally. Although most of the methods shown only manipulate properties, you're can include non-property methods. For example, the getProps() method returns the list of property getters and setters.. Note that any method included inside the constructor that does not possess a method pointer is a private method. A private method can be used only by the object itself—it cannot be called from outside the object.

After declaring the method pointers, the myObject() function defines a set of nested functions. Only instances of myObject will have access to these private functions. Consider the following:

var myObj = new myObject("Tom","Duffy"); alert(getProp1());

The second line throws an error indicating that getprop1() is undefined. The correct call looks something like this:


That code will display "Tom"—as it should.

Finally, note that the private function called privateMethod() is invisible outside of the myObject function. By omitting the method pointer to privateMethod() and nesting it within the myObject() function, neither a calling script nor an object instance can make use of privateMethod(). It exists solely to provide some mechanism to another public method inside the object—in this case the trivial testPrivateMethod() function.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date