a String.prototype's "this" doesn't return a string?
To make sure you're always getting a string, trying using this code:
String.prototype.doNothing = function() {
return this.toString();
};
alert(typeof 'foo'.doNothing())
alert(typeof 'foo')
In your original code, this
is being returned as the string object and not the actual string.
Here's a thorough overview of the this
keyword. Basically, JavaScript converts it into an object, if it wasn't one.
The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisValue, and a caller provided argumentsList:
- If the function code is strict code, set the ThisBinding to thisValue.
- Else if thisValue is null or undefined, set the ThisBinding to the global object.
- Else if Type(thisValue) is not Object, set the ThisBinding to ToObject(thisValue).
- Else set the ThisBinding to thisValue
Same thing happens to Numbers and Booleans. A similar DoNothing
function would return a type of object.
Run your code in strict
mode to get your expected result!