Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a String.prototype's "this" doesn't return a string?

Tags:

javascript

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.

like image 422
adamJLev Avatar asked Feb 28 '11 19:02

adamJLev


3 Answers

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.

like image 126
McHerbie Avatar answered Sep 23 '22 19:09

McHerbie


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:

  1. If the function code is strict code, set the ThisBinding to thisValue.
  2. Else if thisValue is null or undefined, set the ThisBinding to the global object.
  3. Else if Type(thisValue) is not Object, set the ThisBinding to ToObject(thisValue).
  4. Else set the ThisBinding to thisValue

Same thing happens to Numbers and Booleans. A similar DoNothing function would return a type of object.

like image 27
Bob Avatar answered Sep 19 '22 19:09

Bob


Run your code in strict mode to get your expected result!

like image 7
everconfusedGuy Avatar answered Sep 19 '22 19:09

everconfusedGuy