HTML and CSS Reference
In-Depth Information
methods on booleans. Listing 5.27 shows an example in which this might produce
unexpected results.
Listing 5.27 Calling methods with booleans as this
Boolean.prototype.not = function () {
return !this;
};
TestCase("BooleanTest", {
"test should flip value of true": function () {
assertFalse(true.not());
assertFalse(Boolean.prototype.not.call(true));
},
"test should flip value of false": function () {
// Oops! Both fail, false.not() == false
assertTrue(false.not());
assertTrue(Boolean.prototype.not.call(false));
}
});
This method does not work as expected because the primitive booleans are
converted to Boolean objects when used as this . Boolean coercion of an object
always produces true , and using the unary logical not operator on true unsur-
prisingly results in false . ECMAScript 5 strict mode fixes this as well, by avoiding
the object conversion before using a value as this .
The apply method is similar to call , except it only expects two arguments;
the first argument is the this value as with call and its second argument is an
array of arguments to pass to the function being called. The second argument does
not need to be an actual array object; any array-like object will do, meaning that
apply can be used to chain function calls by passing arguments as the second
argument to apply .
As an example, apply could be used to sum all numbers in an array. First con-
sider the function in Listing 5.28, which accepts an arbitrary amount of arguments,
assumes they're numbers, and returns the sum.
Listing 5.28 Summing numbers
function sum() {
var total = 0;
for (var i = 0, l = arguments.length; i < l; i++) {
total += arguments[i];
 
Search WWH ::




Custom Search