What is going on here? Just when I thought I knew JS inside and out, this gem comes up.
String.prototype.doNothing = function() {
return this;
};
alert(typeof 'foo'.doNothing()) // object
alert(typeof 'foo') // string
http://jsfiddle.net/dJBmf/
This is breaking some things that expect a string, such as jQuery's .text(str)
method.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With