Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 7, 2019 04:29 pm GMT

Tired of Guessing What 'this' Is Referring To?

What is this?

If you are new to JavaScript it is only a matter of time before you run into the concept of the this keyword. The this keyword is the JavaScript context object in which the current code is executing. When JavaScript code is executing, it is running within a specific execution context. When a browser first loads a script, it is in the global execution context. However, once a function is called a new execution context is formed and pushed onto the call stack.

At first determining the value of this might feel a little like magic and have you throwing console.log()'s in your code. However, there are only a few rules that you can go through to figure out what this is referring to. The most important thing to first remember is that the value of this depends on how a function is called. Looking at where the function is defined will not help you.

Rules for determining the value of this:

First we look to see if the new keyword is used when calling the function. If new is used this inside the function will refer to the brand new object created when new runs Object.Create() under the hood.

Second we see if apply, call, or bind are used when calling the function. this inside the function will refer to the object that is passed in as the argument to apply, call, or bind.

Third, if a function is called as a method, such as obj.method()this will refer to the object that the function is a property of.

Otherwise this is the global object. In a browser, it is the window object. If in strict mode ('use strict'), this will be undefined instead of the global object.

One thing to note is that ES6 arrow functions ignore all the rules above. They do not have their own this, so this is determined lexically. This means that JavaScript will look to its surrounding parent scope to determine what this is referring to.

Why is this even important?

If we think about why we write functions in general we see that functions make it easy to encapsulate and reuse logic. The this keyword lets us decide what context we want when we invoke a function. By using this we can reuse functions or methods within different contexts or with different objects.

If you have any questions, comments, or feedback - please let me know. Follow for new weekly posts about JavaScript, React, Python, and Django!


Original Link: https://dev.to/guin/tired-of-guessing-what-this-is-referring-to-3nfk

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To