Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript string interpreted as object

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!

like image 324
A. Sallai Avatar asked May 01 '14 17:05

A. Sallai


1 Answers

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"
like image 100
epascarello Avatar answered Oct 03 '22 21:10

epascarello