HTML and CSS Reference
In-Depth Information
}
return total;
}
Listing 5.29 shows two test cases for this method. The first test sums a series of
numbers by calling the function with parentheses, whereas the second test sums an
array of numbers via
apply
.
Listing 5.29
Summing numbers with
apply
TestCase("SumTest", {
"test should sum numbers": function () {
assertEquals(15, sum(1, 2, 3, 4, 5));
assertEquals(15, sum.apply(null, [1, 2, 3, 4, 5]));
}
});
Remember, passing
null
as the first argument causes
this
to implicitly bind
to the global object, which is also the case when the function is called as in the first
test. ECMAScript 5 does not implicitly bind the global object, causing
this
to be
undefined
in the first call and
null
in the second.
call
and
apply
are invaluable tools when passing methods as callbacks to
other functions. In the next chapter we will implement a companion method,
Function.prototype.bind
, which can bind an object as
this
to a given
function without calling it immediately.
In this chapter we have covered the theoretical basics of JavaScript functions. We
have seen how to create functions, how to use them as objects, how to call them,
and how to manipulate arguments and the
this
value.
JavaScript functions differ from functions or methods in many other languages
in that they are first class objects, and in the way the execution context and scope
chain work. Also, controlling the
this
value from the caller may be an unfamiliar
way to work with functions, but as we'll see throughout this topic, can be very
useful.
In the next chapter we will continue our look at functions and study some more
interesting use cases as we dive into the concept known as closures.