Java Reference
In-Depth Information
Borrowing Methods from Prototypes
It is possible to
borrow
methods from objects without having to inherit all their properties
and methods. This is done by making a reference to the function that you want to borrow
(that is, without parentheses so that it isn't invoked).
For example, the
batman
object does not have any of the super-power methods that the
superman
object has, but we can create a reference to them that can then be used by an-
other object. For example, we can create a
fly()
function by referencing the
superman
object's
fly
method:
fly = superman.fly;
<< function () {
return "Up, up and away! " + this.name + " soars
through the
↵
air!"
}
This method can now be called on another object using the
call
method that all functions
have:
fly.call(batman);
<< "Up, up and away! Batman soars through the air!"
Borrowing Array Methods
One of the most common uses of borrowing methods is from arrays. There are many
array-
like
objects in JavaScript, such as the
arguments
object that's available in functions and
the node lists that many of the DOM methods return. These act like arrays but are missing a
lot of the methods arrays have—often it would be convenient if they had them.
For example, the
arguments
object can use the
slice
method from the
Array
con-
structor's prototype by assigning a variable that points to it:
slice = Array.prototype.slice;
