Java Reference
In-Depth Information
The
apply()
and
call()
methods are used for the same purpose. Both are used to
call a method for an object. They differ only in argument types. The first argument to both
methods are an object in whose context the method is called. The
apply()
method lets
you specify the arguments to the method in an array whereas the
call()
method lets you
specify each argument separately. These methods let you call a method of an object on
any other objects. You can use these methods to call the overridden methods of an object.
The following code shows how to call the
toString()
method of the
Object.
prototype
on a
String
object:
// Create a String object
var str = new String("Hello");
// Call the toString() method of the String object
var stringToString = str.toString();
// Call the toString() method of the Object.prototype object on str
var objectToString = Object.prototype.toString.call(str);
print("String.toString(): " + stringToString);
print("Object.prototype.toString(): " + objectToString);
String.toString(): Hello
Object.prototype.toString(): [object String]
The
bind()
method binds a function to an object and returns a new function object.
When the new function is called, it executes in the context of the bound object. It takes
variable-length arguments. The first argument is the object that you want to bind with the
function. The rest of the arguments are the arguments you want to bind with the function.
If you bind any arguments to the function, those arguments will be used when you call
the bound function.
Suppose that you want to create a function for the
Point
objects that will compute
the distance of a
Point
from the origin. You can create a
Point
to represent the origin and
bind the
Point.prototype.distance
function to this object to get a new function.
Listing 4-23 demonstrates this technique.
Listing 4-23.
Binding a Function to an Object
// functionbind.js
load("Point.js");
// Create a 2D origin
var origin = new Point(0, 0);
// Create a new method called distanceFromOrigin() by binding
// the distance() method of the Point to the origin object
var distanceFromOrigin = Point.prototype.distance.bind(origin);
Search WWH ::
Custom Search