What does the 'this' keyword mean?

You can think of the 'this' keyword in JavaScript like the use of the word itself.

Say for example;

this book. 
this car. 
this house.

which means we are using the word this to make reference to these items.

In JavaScript, the 'this' keyword also works this way which means we can use it to make reference to a function, an object within the context in which it is called or executed.

Look at the sample below;

console.log(this); // returns the window or global context

The code above means the keyword 'this' would be executed at a global context as it is not being called within a function.

Here’s another example:

const greeting = {
   name: 'jolly',
   sayHello: function() {
   return `hello ${this.name}!!!`; 
  },
};

console.log(greeting.sayHello()); // returns hello jolly!!!

The example above means that the 'this' is making reference to the property of the object in which it is being called i.e it is available within the execution context.

NOTE:

The behaviour of the 'this' keyword in 'strict mode' and non strict mode are different.

For example, if you call this within a function in non strict mode, it would be executed in the global context like so;

// returns the global or window context
function nonStrictModeFunction(){
  return this;
}

Now let’s try and run this in strict mode to see the behaviour;

// returns undefined
function strictModeFunction(){
 'use strict'
  return this;
}

It returns undefined because this was not called as a property of an object or a method.

There are other cool things you would want to learn related to the this keyword which are these prototype methods bind, call and apply.

These methods are very useful when trying to create a new method from a another to either change some of the properties or extend it with extra properties.

Here’s an example of the bind method;

function sayHello(){
  return `hello ${this.name}!!!`;
}

const greetings = { name: 'jolly' };
const newSayHello = sayHello.bind(greetings);
console.log(newSayHello()); // returns hello jolly!!!

It means we using the 'this' context 'bind' to create a new function newSayHello by explicitly binding the object greetings.

Here’s another example with the call method;

function sayHello(){
  return `hello ${this.name}!!!`;
}

const greetings = { name: 'jolly' };
console.log(sayHello.call(greetings)); // returns hello jolly!!!

Using the call method here means that we are using the'this' context to directly execute the function with out creating a new function.

The apply method also works similarly to the call method but accepts extra arguments as an array rather than comma separated values.

You can make reference to the MDN documentation here to learn more.

Happy learning 🚀🚀🚀