Java Reference
In-Depth Information
undefined undefined
Ken Smith
Typically, a constructor does not use a return statement in its body. If it returns no
value or a primitive value, the new object is used, ignoring the primitive value. If it returns
an object, the returned object is used as the value of the invocation of the new operator. It
may sound odd that the return value of the constructor may change the returned object
of the new operator; however, it is a powerful feature of the language. You can use this to
implement a function that can be used as a function as well as a constructor and both
return an object. You can use it for caching an object and returning the cached object
when a new object already exists in the cache. Listing 4-6 shows such a technique.
Listing 4-6. The Contents of the Logger.js File
// Logger.js
// Declare a function object named Logger
function Logger() {
// A private method
function getLogger() {
if (!Logger.logger) {
// Create a new logger and store its reference in
// the looger pproperty of the Logger function
Logger.logger = {log: function(msg) {
print(msg);
}
};
}
return Logger.logger;
}
return getLogger();
}
// Create two logger objects
var logger1 = new Logger(); // A constructor call
var logger2 = new Logger(); // A constructor call
var logger3 = Logger(); // A function call
// Check if the logger is cached
print("logger1 === logger2 is " + (logger1 === logger2));
print("logger1 === logger3 is " + (logger1 === logger3));
logger1.log("Hello 1");
logger2.log("Hello 2");
logger3.log("Hello 3");
 
Search WWH ::




Custom Search