HTML and CSS Reference
In-Depth Information
are not allowed inside blocks, e.g., in an if-else statement. A common situation in
which a function might be conditionally defined is when defining functions that
will smooth over cross-browser differences, by employing feature detection. In
Chapter 10, Feature Detection, we will discuss this topic in depth, and an example
could be that of adding a trim function that trims strings. Some browsers offer
the String.prototype.trim method, and we'd like to use this if it's available.
Listing 5.18 shows a possible way to implement such a function.
Listing 5.18 Conditionally defining a function
var trim;
if (String.prototype.trim) {
trim = function (str) {
return str.trim();
};
} else {
trim = function (str) {
return str.replace(/^\s+ | \s+ $ /g, "");
};
}
Using function declarations in this case would constitute a syntax error as per
the ECMAScript specification. However, most browsers will run the example in
Listing 5.19.
Listing 5.19 Conditional function declaration
// Danger! Don't try this at home
if (String.prototype.trim) {
function trim(str) {
return str.trim();
}
} else {
function trim(str) {
return str.replace(/^\s+ | \s+ $ /g, "");
}
}
When this happens, we always end up with the second implementation due
to function hoisting—the function declarations are hoisted before executing the
conditional statement, and the second implementation always overwrites the first.
An exception to this behavior is found in Firefox, which actually allows function
 
Search WWH ::




Custom Search