So i am messing around with Javascript and one thing caught my attention.
The variable THIS, and working on it i was wondering, if i have this function:
var someFn = function(){ console.log(this); }
and i run someFn() obviously it will console the Window, but is there, anyway i can make that exact same function console a string? And not a object?
I've tried many ways, even:
someFn.call("A Nice String");
But it will break the string into an object on each letter.
Is there any way?
In loose mode, this is always an object. Strings, numbers and booleans will be wrapped (which is what you see, an array-like String object), null and undefined will be replaced with the global object (window in browsers).
If you use strict mode, it will work as expected:
function someFn(){ "use strict"; console.log(this); }
someFn(); // undefined
someFn.call("A nice string"); // A nice string
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