HTML and CSS Reference
In-Depth Information
if (!String.prototype.trim) {
String.prototype.trim = function trim() {
return this.replace(/^\s+ | \s+ $ /g, "");
// Should throw a ReferenceError, true in IE
// Even worse: IE creates two different function objects
assertNotSame(trim, String.prototype.trim);
This is a bleak situation; when faced with named function expressions, Internet
Explorer creates two distinct function objects, leaks the identifier to the containing
scope, and even hoists one of them. These discrepancies make dealing with named
function expressions risky business that can easily introduce obscure bugs. By as-
signing the function expression to a variable with the same name, the duplicated
function object can be avoided (effectively overwritten), but the scope leak and
hoisting will still be there.
I tend to avoid named function expressions, favoring function declarations
inside closures, utilizing different names for different branches if necessary. Of
course, function declarations are hoisted and available in the containing scope as
well—the difference is that this is expected behavior for function declarations,
meaning no nasty surprises. The behavior of function declarations are known and
predictable across browsers, and need no working around.
5.4 The this Keyword
JavaScript's this keyword throws many seasoned developers off. In most object
oriented languages, this (or self ) always points to the receiving object. In most
object oriented languages, using this inside a method always means the object on
which the method was called. This is not necessarily true in JavaScript, even though
it is the default behavior in many cases. The method and method call in Listing 5.23
has this expected behavior.
Listing 5.23 Unsurprising behavior of this
var circle = {
radius: 6,
diameter: function () {
return this.radius * 2;
Search WWH ::

Custom Search