I've discovered some really interesting (read as "horrible") behavior in Safari 5 and Internet Explorer 9. I was using this with great success in Chrome and Firefox.
if (typeof this === 'string') {
doStuffWith(this);
}
Then I test in IE9, and it doesn't work at all. Big surprise. But in Safari, it's intermittent! So I start debugging, and I find that Internet Explorer is always returning false
. But the weirdest thing is that Safari seems to be doing some kind of optimization in its JavaScript VM where it is true
the first time, but false
every time you hit reload!
My brain almost exploded.
So now I've settled on this:
if (this instanceof String || typeof this === 'string')
doStuffWith(this.toString());
}
And now everything works great. Note that you can call "a string".toString()
and it just returns a copy of the string, i.e.
"a string".toString() === new String("a string").toString(); // true
So I'll be using both from now on.