HTML and CSS Reference
In-Depth Information
7.4 Encapsulation and Information Hiding
JavaScript does not have access modifiers such as public , protected , and
private . Additionally, the property attributes DontDelete and ReadOnly
are unavailable to us. As a consequence, the objects we've created so far consist
solely of public properties. In addition to being public, the objects and properties
are also mutable in any context because we are unable to freeze them. This means
our object's internals are open and available for modification by anyone, possibly
compromising the security and integrity of our objects.
When using constructors and their prototypes, it is common to pre-
fix properties with an underscore if they are intended to be private, i.e.,
this. _ privateProperty . Granted, this does not protect the properties in
any way, but it may help users of your code understand which properties to stay
away from. We can improve the situation by turning to closures, which are capable
of producing a scope for which there is no public access.
7.4.1 Private Methods
By using closures, we can create private methods. Actually, they're more like pri-
vate functions , as attaching them to an object effectively makes them public. These
functions will be available to other functions defined in the same scope, but they
will not be available to methods added to the object or its prototype at a later stage.
Listing 7.41 shows an example.
Listing 7.41 Defining a private function
function Circle(radius) {
this.radius = radius;
}
(function (circleProto) {
// Functions declared in this scope are private, and only
// available to other functions declared in the same scope
function ensureValidRadius(radius) {
return radius >= 0;
}
function getRadius() {
return this.radius;
}
function setRadius(radius) {
if (ensureValidRadius(radius)) {
 
 
Search WWH ::




Custom Search