Skip to main content

Explained Simply: “This” Keyword in JavaScript

 

“This” in any programming language is a strange concept to understand due to the ambiguity of the definition.

Simply put, because This is used in many different ways it is difficult to precisely define. The best way to learn this is to learn the many different ways in which this can change.

  1. Start with a simple console.log(this);

By a simple console.log, you can quickly tell gain understanding into what this is. \

console.log(this);

The This keyword is pointing to the global object. “This” is the “world” or the context of which this resides. Whenever you see the curly brackets {} in programming, that means the code residing in a different context. Without curly braces and logging console.log in the open, “This” is simply the global object. For a simple explanation of context, please check out my Youtube video.

2. Next, console.log(this) within a function

function show() {
   console.log(this === window); // true
}

show();

This is a tricky topic inside of functions (no pun intended). When functions are executed in the global scope, the value of this is the window object.

The above function was not executed inside of any other function or object, so by default show was called on the global object.

3. Next, console.log(this) within an object

let person = {
    name: "teddy",
    getName: function() {
        return this.name;
    }
}

console.log(person.getName()) // teddy

In the above example, the “this” object in getName references the person object.

let me = person.getname;
console.log(me()); // undefined

You get undefined instead of “teddy” because when you call a method without specifying its object, Javascript sets “this” to the global object.

let person = {
      name: 'teddy',
      getName: function() {
            return this.name;
      }
}

let teddy = {
      shirt: 'the eagles'
}

let shirt = person.getName.bind(teddy);

console.log(shirt());

4. Lastly, console.log(this) inside an arrow function.

ES6 introduced a new concept called the arrow function. In arrow functions, JavaScript sets the “this” lexically.

This means the arrow function does not create its own execution context, but inherits the “this” from the outer function.

let thisArrowFunction = () => this;
console.log(thisArrowFunction() === window); //true

In this example, there is no outer function so the execution content is the global object.

Comments

Popular posts from this blog

Hoisting In JavaScript Explained Simply

  JavaScript is a weird language. We are all aware of this. But one of the biggest peculiarities is the concept of hoisting. Because hoisting is centered around variable declaration, it confuses beginners to no end. In this blog, I am going to give practical, real-world explanations of hoisting! Hoisting Introduction Hoisting is a default behavior which variables and function are moved to the top of the scope before JS executes.   Even more simply put, it allows you to use variables and functions before declaring them. x = 1; console.log(x); //This is valid and will execute. var x; Essentially, JavaScript is taking “var x;” variable  declaration  and placing it above x = 1. The biggest caveat to hoisting is that it only works with declaration BUT not initialization of variables. console.log(x) //This will be undefined because it is being initialized. var x = 1; Hoisting Functions in Javascript JavaScript engine moves function declarations to the top similar to varia...

Spring Data JPA Many-To-Many Explained Simply

  At a certain point in your Java career, it is inevitable to arrive at a point where you have models that are related to each other but cannot be solved with foreign keys. A good example of a many-to-many relationships is the relationship between rice and sauces. I love ALL types of different rice with different types of sauces. Sometimes I like Jasmine rice with spicy curry, while other times I like sticky rice with soy sauce. In a pinch, I’ve even ate Jasmine rice with soy sauce! *crowd gasps* Overall, many-to-many is a relationship that has infinite amounts of different combinations. Try to apply the rice analogy to a  one-to-many relationship  and it will not work. Many-To-Many Relationships To maintain a many-to-many relationship between two tables in a database, the only way is to have a third table which has a reference to both sides of the table. This table is called a “join” table and each entry in this table will connect the source table and target table. Many-...

CSS ‘>’, ‘+’, ‘~’ Selectors Explained Simply

  Knowing CSS selectors is easily one of the most important aspects of web development. As a former backend developer, it makes me cringe how bad I was at CSS selectors. Not knowing selectors is known to cause mangled front ends and ugly Bootstrap UI’s! Element selectors Descendant selectors Class selectors Id Selectors Child Selectors Adjacent Selectors Pseudo Selectors Element Type Selectors The most basic CSS selectors are Element Type Selectors.  With elements selectors all you are doing is selecting the element. Element selectors are most common when you first setup your CSS and assign very broad actions like fonts, colors, line heights, etc. Very rarely will you use CSS selectors for things like positioning. body { font-family : var ( --body-font ) ; color : var ( --text-dark ) ; } Descendant Selectors The descendant selector is used to match elements that are descended from another matched selector. This selector is easy to spot because it is just a space....