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?

+3


source to share


2 answers


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

      

+3


source


I've had this problem in the past, it seems to insist on outputting an object with each letter as part of an array.

I ended up cheating and using something like:

console.log(this+'')

      



or

console.log(this.toString());

      

+2


source







All Articles