Understanding THIS in Javascript I am lost
So I was messing around with Javascript and one thing caught my attention.
The THIS variable and working on it, I was wondering if I have this function:
var someFn = function(){ console.log(this); }
and I ran someFn (), obviously it will be the Window console, but is there anyway I can make this same function console a string? Not an object?
I've tried many ways, even:
someFn.call("A Nice String");
But it splits the string into an object for each letter.
Is there a way?
source to share
In free mode, this
it is always an object. Strings, numbers and booleans will be wrapped (that's what you see, an array String
) null
and undefined
replaced with a global object ( window
in browsers).
If you are using strict mode , it will work as expected:
function someFn(){ "use strict"; console.log(this); }
someFn(); // undefined
someFn.call("A nice string"); // A nice string
source to share