Java Reference
In-Depth Information
Listing 4-16 show code that creates a logger object that has only one property called
log that is a function. It uses the Object.bindProperties() method to bind the property
of the object to the global object referenced by this . Once, the bind takes place, you can
use the function log() as if it is a global function. When the code is loaded, it prints the
location of the log file.
Listing 4-16. Binding an Object's Properties to the Global Object
// loadglobals.js
// Create a function obejct using a function expression
var Logger = function () {
var LOG_FILE = new java.io.File("nashorn_app.log");
var printer = new java.io.PrintWriter(
new java.io.FileWriter(LOG_FILE, true /*append*/), true
/*autoflush*/);
this.log = function (msg) {
printer["println(String)"](java.time.LocalDateTime.now() +
": " + msg);
};
// Print the path for the log file
print("Logs using the log(msg) global function will be written to " +
LOG_FILE.absolutePath);
};
// Bind a Logger object to the global object.
// Here, this refers to the global object
Object.bindProperties(this, new Logger());
The following code loads the loadglobals.js file and uses the log() function as if it
is a global function. You may get a different output. The logged messages will be stored in
the file located printed in the output. You can use this technique to import as many global
objects int the global scope you need. All that you need to do is to add all such properties
to an object and bind that object to the global object this :
// Load the globals
load("loadglobals.js");
// Now you can use the log() method as a global function
log("Hello logger!");
Logs using the log(msg) global function will be written to
C:\nashorn_app.log
 
Search WWH ::




Custom Search