Javascript string interpreted as an object

It probably has nothing to do with the production point of view, but I would like to know why this behaves the way it happens. The string literal is 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 need to call

 this.toString() 

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

+8
javascript string
source share
1 answer

From the MDN () call :

thisArg

The significance of this provided for pleasure. Note that this may not be the actual value considered by the method: if the method is a function in non-lax code, null and undefined will be replaced with a global object, and primitive values ​​will be placed in a box .

The primitives [aka numbers / strings] are placed in a container object, so it works the same way you see it.

So basically this

 > var x = "string"; > typeof x "string" > var temp = new String(x); > typeof temp "object" 
+6
source share

All Articles