↑
Main Page
Public, protected, and private
Scope
Programmers in any language understand the concept of
scope
, meaning the area in which certain vari-
ables are accessible.
Public, protected, and private
In traditional object-oriented programming, a lot of focus is placed on the public and private scopes. An
object’s properties in the
public
scope can be accessed from outside the object, meaning that after a devel-
oper creates an instance of the object, that property can be used. Properties in the
private
scope, however,
can only be accessed from within the object itself, meaning that these properties don’t exist to the out-
side world. This also means that subclasses of the class defining the private properties and methods
can’t access them either.
More recently, another scope has become popular:
protected
. Although different languages have different
rules for the protected scope, it generally is used to define properties and methods that act private except
that they are accessible by subclasses.
The discussion of these scopes in reference to ECMAScript is almost a moot point because only one
scope of these three exists: the public scope. All properties and methods of all objects in ECMAScript are
public. You must take great care, therefore, when defining your own classes and objects. Keep in mind
that all properties and methods are public by default.
This problem has been tackled by many developers online trying to come up with effective property
scoping schemes. Due to the lack of a private scope, a convention was developed to indicate which prop-
erties and methods should be considered private. This convention involves adding two underscores
before and after the actual property name. For example:
obj.__color__ = “red”;
In this code, the
color
property is intended to be private. Remember, adding these underscores doesn’t
change the fact that the property is public; it just indicates to other developers that it should be consid-
ered private.
Some developers also prefer to use a single underscore to indicate private members, such as
obj._color
.
Static is not static
The
static
scope defines properties and methods accessible all the time from one location. In Java, classes
can have static properties and methods that are accessible without instantiating an object of that class,
such as
java.net.URLEncoder
, whose function
encode()
is a static method.
Strictly speaking, ECMAScript doesn’t have a static scope. It can, however, provide properties and meth-
ods on constructors. Remember, constructors are just functions. Functions are objects, and objects can
have properties and methods. For instance:
function sayHi() {
alert(“hi”);
}
88
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 88
Free JavaScript Editor
Ajax Editor
©
→ R7