1. Computing

Object Oriented JavaScript

19. Public Access to Private Methods

From , former About.com Guide

Not only properties can be defined as private to an object constructor, you can also define methods as private to the constructor as well. Here's a very simple example where the method _b() is private to our example object (note that using an underscore as the first character of a private method's name is a common naming convention for making private methods readily identifiable, you are not forced to follow the convention though and can name private methods whatever you like).





function example(param) {
  var _b = function(x) {
    return x+1;
  }
  this.x = _b(param);
}

Our method _b() is defined within the constructor and therefore we know that it must exist when the rest of the code within our constructor runs. This avoids the problem we can have with a public method perhaps not existing at the time the object constructor is run.

What happens though when we find that we need to be able to use the method from elsewhere as well as from within the constructor? The solution here is to create a privileged method that points to the private one. We can do this by adding just one extra line to our constructor.


function example(param) {
  var _b = function(x) {
    return x+1;
  }
  this.x = _b(param);
  this.b = _b;
}

We now have a public method for our object and calling example.b() allows the method which was private to the constructor to be called from anywhere while the example object exists. Should example.b get redefined at any time it still doesn't change the _b method used in the example constructor which will therefore continue to work as expected.

All the Object Oriented JavaScript Tutorials

  1. What is Object Oriented JavaScript?
  2. The Benefits of OO JavaScript
  3. JavaScript's Built in Objects
  4. Extending Built In Objects
  5. Creating Objects from Existing Objects
  6. Creating New Objects Without Copying Existing Ones
  7. Dot Notation and "this"
  8. prototype
  9. Inheritance and "constructor"
  10. Associative Array Notation
  11. Create Method if Doesn't Exist
  12. "self" and Multiple Objects
  13. Defining Objects with JSON
  14. Namespaces
  15. Lazy Definition
  16. Extending Methods
  17. Copying Objects
  18. Private Properties and Privileged Methods
  19. Public Access to Private Methods
  20. Chaining Methods
  21. Singletons

©2013 About.com. All rights reserved.