methods and encapsulation
An object method is a function that is attached to an object. Typically a method performs some action relating to its object. Like private properties, private methods may be used only by code internal to the object and are inaccessible elsewhere, whereas public methods are for outside use, and form part of the interface of the object with other code.
Private properties may be accessed by means of public methods. In this sense, the private object properties are encapsulated data, because the object’s interface controls access to them.
To access a public member of an object from code other than that of
the constructor and the object’s public methods,
connect the object variable name with a period “
.” with the
function keyword. This is a convenient way to
create an object method in a constructor.
Let’s build on the example from the previous section, adding private and public methods.
The data of
prop1 is encapsulated: it can be
accessed or altered only by calling methods
Note that the private member declarations must precede their use, because really they are just variables in the scope of the constructor function.
- members can only be accessed within constructor and public
method code, using
- methods can access private members, but not public ones
- members can only be accessed within constructor and public method code, using
- members can be accessed anywhere using the dot notation
- methods can access both public and private members