8

Probably irrelevant from a production standpoint, but I'd like to know why this behaves the way it does. The string literal gets interpreted as an object.

function fancyCallback(callback) {
  callback(this);
  console.log(typeof this); // just to see it really is an object
}

fancyCallback.call('string here', console.log);

I have to call

this.toString()

inside the function if I want the expected output. I know strings are objects in javascript (which is lovely) but in a simple console.log('abc'), they are naturally interpreted as strings. Why is that? Is this useful in any way? Please ignore the fact that fancyCallback is defined in the global scope!

5
  • I believe it is because of the way variable definitions are in js. Commented May 1, 2014 at 17:24
  • console.log() simply calls the toString method on the string Commented May 1, 2014 at 17:25
  • this returns false: (function() {return this;}).call('string here')==='string here' Maybe the object was modified in some way. Commented May 1, 2014 at 17:26
  • @levi I added console.log(this) to his function, Chrome displayed String {0: "s", 1: "t", 2: "r", 3: "i", 4: "n", 5: "g", 6: " ", 7: "h", 8: "e", 9: "r", 10: "e", length: 11, formatUnicorn: function, truncate: function, splitOnLast: function, contains: function}. Commented May 1, 2014 at 17:26
  • 1
    @levi that is not true, try deleting the typeof keyword inside the function so it says console.log(this). it does not call toString() on it Commented May 1, 2014 at 17:27

1 Answer 1

6

From MDN call() :

thisArg

The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

Primitives [aka numbers/strings] are placed into a container object, so it is working just like you are seeing it.

So what it is basically doing is

> var x = "string";
> typeof x
"string"
> var temp = new String(x);
> typeof temp
"object"
Sign up to request clarification or add additional context in comments.

3 Comments

never heard the term "boxed"! honestly, I just love javascript even more for this. thanks!
added a little bit more of an explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.