Encapsulation objects
Encapsulation is the name given to OOP’s capability to hide data and instructions inside an object. How this is achieved varies from language to language, but in JavaScript any variables declared inside the constructor function are available only from within the object; they are invisible from outside. The same is true of any function declared inside the constructor function.
Such variables and functions become accessible to the outside world only when they are assigned with the this keyword; they then become properties and methods of the object.
Let’s look at an example:
function Box(width, length, height) { function volume(a,b,c) { return a*b*c; } this.boxVolume = volume(width, length, height); } var crate = new Box(5,4,3); alert("Volume = " + crate.boxVolume); // works correctly alert(volume(5,4,3)); // fails as function volume() is invisible
In the preceding example, the function volume(a,b,c) cannot be called from any place outside the constructor function as it has not been assigned to an object method by using this. However, the property crate.boxVolume is available outside the constructor function; even though it uses the function volume() to calculate its value, it only does so inside the constructor function.
If you don’t “register” methods and properties using this, they are not available outside. Such methods and properties are referred to as private.