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!
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"
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