Search within TutorialsPark

Javascript Function: Private Variables

Learn to create and use private variables and methods.

Javascript Functions: Private Variables

In JavaScript, you cannot create private members, since all object properties are public.But you can create private variables

Variables defined within a function are private because it cannot be accessed from outside the function, but this issue can be overcome by creating closures within function, which can access these variables using a scope chain.

A privileged method is defined a public method which can access private variables/functions.

In the demo below, the methods fetchName() and assignName() are privileged and hence can access the private variable name

Syntax: Javascript Function Private Variables and Privileged Methods.

Example: Javascript Functions : Private Variables and Privileged Methods.

Give it a TRY! » Note: Since both the methods are defined within the constructor, hence they can be accessed via scope chain

Javascript Functions : Static Private Variables

Another way to create privileged methods is to create a private scope and define within it private variables and functions.

In this technique, a private scope is used to enclose the constructorand its methods, public methods are defined using the prototype pattern and constructors are defined using function expression to create global functions.

In the demo below, the constructor Company has access to private variable name and methods fetchName() and assignName(), thus the variable name can be used by all instances.

Example: JavaScript Functions : Static Private Variables

Example: JavaScript String Object : Properties

Give it a TRY! » Note: Calling assignName() on one instance has an effect on all other instance.

Javascript Function: Module Pattern

The Module Pattern are created using singletons. Singletons are object which will have only one instance ever.They are generally created using object literal notation.

The module pattern is used to extend the basic singletons by add to it some private variables and privileged methods.Module patterns use an anonymous function which returns an object.

Example: JavaScript Function : Module Pattern

Give it a TRY! » Note: The methods getComponentCount() and registerComponent() are privileged and have access to the array components