In order to properly implement "data hiding", the
dimension property from the code on the previous page just needs to be defined differently, specifically
with the keyword “var” rather than “this”, as follows:
|
function Square(size) {
var dimension = size;
this.area = size * size;
}
var object1 = new Square(4); alert("Dimension: " + object1.dimension + "\nArea: " + object1.area);
|
This results in the following:

OK,
so we can hide the dimension property. Can we still access it
though? Sure. Modifying our code to provide an “accessor”
method:
|
function Square(size) {
var dimension = size;
this.area = size * size;
this.getDimension = function() { return dimension; }
var object1 = new Square(4); alert("Dimension: " + object1.getDimension() + "\nArea: " + object1.area);
}
|
Results in the following:

For the
curious, the mechanism by which this is accomplished is called a
"closure". Just like with object oriented programming in general
though, we don't need to know how it is accomplished ("implementation
details"), we just need to know how to use it ("interface").
Think of "this" within an object constructor as the "public" access
modifier in other OO languages, and "var" as "private". This
would actually make Javascript MORE object oriented than PHP4 (though
arguably less so than PHP5).
Interestingly,
Perl implements Object Orientation in much the same way as Javascript
(via closures), with regard to which Foldoc says "other languages, such as Perl and VB, permit,
but do not enforce OOP." Go ahead and add Javascript to the list too.