Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding THIS in Javascript, i got lost

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?

like image 478
Walter Lange Avatar asked Feb 22 '26 16:02

Walter Lange


1 Answers

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
like image 135
Bergi Avatar answered Feb 25 '26 04:02

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!