HTML and CSS Reference
In-Depth Information
In this example, the return value is undefined because setting b does not
update arguments[1] when no value was passed to b . Thus, arguments[1] is
still undefined , which causes arguments[0] to be undefined . a did receive
a value and is still linked to the arguments object, meaning that the returned
value is undefined . Not all browsers do this by the spec, so your mileage may
vary with the above examples.
This relationship may be confusing, and in some cases can be the source of
mysterious bugs. A good piece of advice is to be careful when modifying function
parameters, especially in functions that use both the formal parameters and the
arguments object. In most cases defining a new variable is a much sounder strategy
than tampering with formal parameters or arguments . For the reasons stated,
ECMAScript 5, the next version of JavaScript, removes this feature in strict mode.
Strict mode is discussed in detail in Chapter 8, ECMAScript 5th Edition.
5.3 Scope and Execution Context
JavaScript only has two kinds of scope; global scope and function scope. This might
be confusing to developers used to block scope. Listing 5.12 shows an example.
Listing 5.12 Function scope
"test scope": function () {
function sum() {
assertUndefined(i);
assertException(function () {
assertUndefined(someVar);
}, "ReferenceError");
var total = arguments[0];
if (arguments.length > 1) {
for(vari=1,l=arguments.length; i < l; i++) {
total += arguments[i];
}
}
assertEquals(5, i);
return total;
}
sum(1, 2, 3, 4, 5);
}
 
 
Search WWH ::




Custom Search