Start United States USA — software Demystifying How 'this' Works in JavaScript

Demystifying How 'this' Works in JavaScript

150
0
TEILEN

It’s something used all the time in Javascript, but often what it refers to is a mystery. Let’s look at how this works in Javascript in different contexts.
Join the DZone community and get the full member experience. It’s something used in JavaScript, but it is often a mystery. In JavaScript, this works quite differently from other programming languages – and it works differently depending on if you are using strict mode or not. If you find it hard, you aren’t alone. Let’s look at exactly how this works and remove any confusion about its meaning in various contexts. this is a keyword in JavaScript which refers to a property or set of properties within a certain context. The context we use this in alters its properties. In the global context, this refers to the global object – which in the browser is a window but is globalThis is in Node. JS and other implementations of JavaScript. Outside of any functions or code, this is always the case. However, in different places, this means different things. In a function, this still refers to the global object. If we reference this in a function, it will, by default, reference the window or globalThis object: In strict mode, however, this inside a function is undefined. this is a little confusing at first, but the reason for this is that we need to add this object onto myFunction – JavaScript in strict mode won’t default it to the global object. To do that, we have to use call(). In the example below, I’ve turned myObject into this variable: call() runs myFunction and attaches myObject to this keyword. If we don’t use call and run myFunction(), the function will return an error, as this.firstName will be undefined. You can also call a function with an empty this, which you can then append data to inside your function. this gives us a new space to define variables on our this object, rather than being polluted with data from the global this object: As you can see, the behavior is quite different depending on if we’re using strict mode or not – so it’s essential you do some tests before changing your code between the two modes.

Continue reading...