HTML and CSS Reference
In-Depth Information
Listing 5.25
Calling a function as a method on an object
function addToArray() {
var targetArr = arguments[0];
arguments.slice = Array.prototype.slice;
var add = arguments.slice(1);
return targetArr.concat(add);
}
Calling the
addToArray
function will work exactly as the one presented in
Listing 5.8. The ECMAScript specification specifically calls for many built-in meth-
ods to be generic, allowing them to be used with other objects that exhibit the right
qualities. For instance, the
arguments
object has both a
length
property and
numeric indexes, which satisfies
Array.prototype.slice
's requirements.
5.4.2 Explicitly Setting
this
When all we want is to control the value of
this
for a specific method call, it
is much better to explicitly do so using the function's
call
or
apply
methods.
The
Function.prototype.call
method calls a function with the first ar-
gument as
this
. Additional arguments are passed to the function when calling
it. The first example of
addToArray
in Listing 5.8 used this method call
Ar-
ray.prototype.slice
with
arguments
as
this
. Another example can be
found in our previous
circle
example, as Listing 5.26 shows.
Listing 5.26
Using
call
assertEquals(10, circle.diameter.call({ radius: 5 }));
Here we pass an object literal that defines a
radius
property as the
this
when calling
circle.diameter
.
5.4.3 Using Primitives As
this
The first argument to
call
can be any object, even
null
. When passing
null
,
the global object will be used as the
this
value. As we will see in Chapter 8,
ECMAScript 5th Edition,
this is about to change—in ECMAScript5 strict mode,
passing
null
as the
this
value causes
this
to be
null
, not the global object.
When passing primitive types, such as a string or boolean, as the
this
value,
the value is wrapped in an object. This can be troublesome, e.g., when calling