This section provides a tutorial example on how to Function object inherited properties and methods.
Because a function is an object of the Function type, it has some interesting inherited properties and methods:
"length" - A property represents the number of arguments expected by this function.
"apply" - A method to apply (execute) this function on a specified object with specified parameters in an array.
"call" - A method to call (execute) this function on a specified object with specified parameters.
"toString" - A method to return the body of this function as a string.
The tutorial example below shows you how to use the properties and methods inherited in a Function object:
// Function_Properties_and_Methods.js
// Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
var sign = new Function("name",
"this.signature = name;"
)
println("Function body: " + sign.toString());
println("# of parameters: " + sign.length);
// Executing it on the current object
sign("Herong");
println("this.signature: " + this.signature);
// Applying it on another object
var java = new Object();
sign.apply(java, new Array("Sun"));
println("java.signature: " + java.signature);
// Calling it on another object
var pc = new Object();
sign.call(pc, "IBM");
println("pc.signature: " + pc.signature);
Run this JavaScript file with "jrunscript" in a command window, you will get:
Function body:
function anonymous(name) {
this.signature = name;
}
# of parameters: 1
this.signature: Herong
java.signature: Sun
pc.signature: IBM
Very cool. Everything worked as I expected. One small surprise is that the name of a function object
created with the Function constructor is "anonymous".