Object-oriented JavaScript
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.

Methods in JavaScript are typically implemented as nested functions, whose code lies within the code body of the object constructor.

Variables defined within a JavaScript function persist so long as another object is referring to them. In this way, local variables defined within a constructor persist, so long as methods of an object created by the constructor refer to them, especially, after the constructor function exits.

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 member name.

	object_variable.property_name
	object_variable.method_name()

In JavaScript, unnamed functions can be defined the function keyword. This is a convenient way to create an object method in a constructor.

example: methods, public and private

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 meth2 and meth4.

Note that the private member declarations must precede their use, because really they are just variables in the scope of the constructor function.

summary of object member access

private
  • members can only be accessed within constructor and public method code, using this.
  • methods can access private members, but not public ones
public
  • members can be accessed anywhere using the dot notation
  • methods can access both public and private members

See

JavaScript Guide: Working with objects