Java Reference
In-Depth Information
logger1 === logger2 is true
logger1 === logger3 is true
Hello 1
Hello 2
Hello 3
When
Logger
is called for the first time, as a function or a constructor, it creates
an object with a
log()
method, caches the object in the
logger
property of the
Logger
function, and returns the object. When
Logger
is called again, it simply returns the
cached object.
Using a constructor, you can maintain private state for objects. This is done using
closure. If you define a variable with the keyword
var
inside a function, that variable
has local scope. It is only accessible inside the function. A nested function captures its
enclosing scope including the local variables declared in its outer function. Listing 4-7
demonstrates the concept of maintaining the private state for an object using a constructor.
It creates a
Sequence
object that maintains the current value that is accessible only
through the methods
curValue()
and
nextValue()
. Notice that when the object
is created, the local variable
currentValue
is captured by both function. When the
functions are called, they work on the same captured variables, as shown in the output.
Listing 4-7.
The Contents of the Sequence.js File
// Sequence.js
// This object generates strictly increasing sequence numbers
function Sequence() {
var currentValue = 0;
// Using Nashorn extension syntax to define one-liner functions
this.nextValue = function () ++currentValue;
this.curValue = function () currentValue;
}
// Create a Sequence object
var empId = new Sequence();
print("empId sequence...");
printf("Current Value = %d, next Value = %d", empId.curValue(),
empId.nextValue());
printf("Current Value = %d, next Value = %d", empId.curValue(),
empId.nextValue());
printf("Current Value = %d, next Value = %d", empId.curValue(),
empId.nextValue());
Search WWH ::
Custom Search