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
- What is Object Oriented JavaScript?
- The Benefits of OO JavaScript
- JavaScript's Built in Objects
- Extending Built In Objects
- Creating Objects from Existing Objects
- Creating New Objects Without Copying Existing Ones
- Dot Notation and "this"
- prototype
- Inheritance and "constructor"
- Associative Array Notation
- Create Method if Doesn't Exist
- "self" and Multiple Objects
- Defining Objects with JSON
- Namespaces
- Lazy Definition
- Extending Methods
- Copying Objects
- Private Properties and Privileged Methods
- Public Access to Private Methods
- Chaining Methods
- Singletons
