Search code examples
javascriptprototypethis

JavaScript's *this* keyword points to the window from within string.prototype


Okay, this will probably earn me the Headslam of the Day badge.

Why is this pointing at window in the following code?

if (!String.prototype.Trim)
{
    String.prototype.Trim = function()
    {
        var result = this.replace(/^\s+|\s+$/g, "");
        return result;
    };
}

As I understand it, this should evaluate to the value of the current string instance. Instead, it's evaluating to the current window object. Thus, the following fails miserably:

var baz = 'foo bar      '.Trim();

Note that this code has been used for quite some time, and is based on code I see advertised all over the place on the intartoobs. So this pattern seems to be the recommended way of doing this. I can't figure out why this isn't pointing to the data I think it should be pointing at. (In Visual Studio, when I hover over it, or view it in the Watches window, it shows up as [object window]).

(IE 8 [32-bit]; Win7; plain-ole HTML page.)


Solution

  • In Visual Studio, when I hover over it, or view it in the Watches window, it shows up as [object window]

    Sounds like a scope resolution bug in VS. There's no way this can be a bug in IE or else thousands of prototypal functions would break.