Understanding the JavaScript "this" Keyword

  • Understanding the JavaScript "this" Keyword

Now friends here, JavaScript programmers who find the keyword "this" confusing, are you a part of sziler and other user group? We are writing this article to explain to you in more detail, in order to eliminate any uncertainty that may be related to this training, such as whether you are a member or a member.

Here on these topics: What does this JavaScript keyword mean? You will see how you can apply this practically to your JavaScript program and how you will process it. These have been some of the typical queries made for this keyword by newcomers and even some seasoned JavaScript developers. You need to pay attention to other painstaking queries.

This article is for you if you're one of the developers who is curious about the meaning of this keyword. To prevent misunderstandings and, of course, coding errors, investigate how this is used in various scenarios and become familiar with some gotchas.

"this" Located Within the Global Scope

In general context this returns the window object as long as it is outside of a function. This is the piece of code we present to you: Global context means you don't put it inside a function. You must know this.

 

if(true) {
  console.log(this) // returns window object
}

let i = 2
while(i < 10) {
  console.log(this) // returns window object till i === 9
  i++
}

 

If you run the above code, you'd get the window object.

"this" Inside Functions ( Methods )

Now my friends as the techdataz team: I would like to tell you that when used inside functions, you will express the object to which the function is bound. The exception is if you use it in a standalone function; actually it usually returns the window object in this case. Let's move forward by looking at some examples together.

In the example below, the "sayName" function is inside the me object, remember that it's an enclosing part (i.e. it's a method). In such cases, "this" refers to the object containing the function.

 

function sayName() {
  return `My name is ${this.name}`
}

const me = {
  name: "Kingsley",
  sayName: sayName
}

console.log(me.sayName()) // My name is Kingsley

 

Since I am the object, I will say this.The name contained within the sayName function is identical to mine.name.

If the function is invoked, whatever is on the left side of the function will be this, to put it another way. This implies that you can reuse the sayName function across several objects, and it will always refer to a separate context.

Now, as was already indicated, when used inside a standalone method, this returns the window object. This is due to the default binding of a standalone function to the window object:

 

function talk() {
  return this
}

talk() // returns the window object

 

I would like to say that calling talk() is the same as calling window.talk() and you will encounter the same function in similar operations. So everything on the left side of the function is automatically converted to this.

As a side note, the this keyword in the function behaves differently in JavaScript's strict mode: the system determines the behavior by taking action on you. and (returns undefined). This is also something to keep in mind when using UI libraries (eg React) that use strict mode.

Using "this" With Function.bind()

In some circumstances, like in the previous section, you might not be able to simply add the function as a method to an object:

Perhaps you are taking the item out of a library and it is not yours. You cannot simply alter the object because it is immutable. In situations like this, you can still use the Function.bind() method to run the function statement independently of the object.

Even though the sayName function in the following example isn't a method on the me object, You nonetheless bound it using the bind() function:

 

function sayName() {
  return `My name is ${this.name}`
}

const me = {
  name: "Kingsley"
}

const meTalk = sayName.bind(me)

meTalk() // My name is Kingsley

 

Now, friends as bind(): whatever object you pass to the function, what you need to pay attention to in that function call is that it is used as its value.

In summary, we would like to tell you that you can use the function in any function like binding () and so on and pass it to a new binding (to an object) And this object will overwrite the meaning of this inside that function.

Using "this" With Function.call()

What if you just want to invoke the function after binding it to its context and don't want to return a brand-new function? The call() method can help with it.

 

function sayName() {
  return `My name is ${this.name}`
}

const me = {
  name: "Kingsley"
}

sayName.call(me) // My name is Kingsley

 

The call() method executes the function immediately, rather than returning a function like or otherwise. If it doesn't run, type the command again with enter:

Now friends are usually in such cases If the function requires a parameter, you can pass it through the call () method. Actually, in the following example, you pass the language to the sayName() function, so you can use it to return different messages conditionally and uniquely:

 

function sayName(lang) {
  if (lang === "en") {
    return `My name is ${this.name}`
  } else if (lang === "it") {
    return `Io sono ${this.name}`
  }
}

const me = {
  name: "Kingsley"
}

sayName.call(me, 'en') // My name is Kingsley
sayName.call(me, 'it') // Io sono Kingsley

 

As you can see, the second argument to the call() method allows you to simply give any parameter you desire to the function. Additionally, you can pass as many parameters as you like.

The call() and bind() methods are extremely similar to the apply() function. The only distinction is that with call(), you can pass several arguments by separating them with commas, whereas with apply(), you can pass multiple arguments inside an array.

In conclusion, you can call functions using a different object using the bind(), call(), and apply() methods without there being any connection between the two objects ( the function isn't a method on the object ).

"this" Inside Constructor Functions

If you call a function with a new keyword, it creates a this object and returns it:

 

function person(name){
  this.name = name
}

const me = new person("Kingsley")
const her = new person("Sarah")
const him = new person("Jake")

me.name // Kingsley
her.name // Sarah
him.name // Jake

 

You have now created three different objects from the same function in the above code. Actually friends are the objects you have created: The new keyword automatically creates a link between the created object and the this keyword inside the function. Do not forget this.

"this" Inside Callback Functions

Regular functions and callback functions are distinct. Callback functions can be executed right away after the primary one has done running since they are functions that are passed to another function as an argument.

If the this keyword is used inside callback functions, it relates to a completely distinct context:

 

function person(name){
  this.name = name
  setTimeout(function() {
    console.log(this)
  }, 1000)
}

const me = new person("Kingsley") // returns the window object

 

The window object will be logged as the value of this after a brief call to the person constructor method and creation of a new me object. In a callback function, this therefore refers to the window object rather than the "constructed" object.

There are two solutions for this. The first approach is using bind() to attach the person function to the just-created object:

 

function person(name){
  this.name = name
  setTimeout(function() {
    console.log(this)
  }.bind(this), 1000)
}

const me = new person("Kingsley") // returns the me object

 

This in the callback will now point to the same this as the constructor function (the me object) after the aforementioned modification. The second way to solve the problem of this in callback functions is by using arrow functions.

"this" Inside Arrow Functions

Compared to conventional functions, arrow functions are unique. Your callback function might be converted to an arrow function. You no longer require bind() since arrow functions immediately bind to the freshly created object:

 

function person(name){
  this.name = name
  setTimeout(() => {
    console.log(this)
  }, 1000)
}

const me = new person("Kingsley") // returns the me object

 

Learn More About JavaScript

In general, we recommend that you proceed from the water sample. It is very important for you to know the keyword "this" and what it means in all the different contexts in JavaScript. In fact, you have learned everything about this and that in this content.

If you're new to JavaScript, we'd love to learn about all of the unique fundamentals of JavaScript and how it works, and it will be of great benefit to you. As the Techdataz team, do not hesitate to send us an e-mail about the different issues that you are stuck with.


Newsletter

wave

Related Articles

wave
How to Use Functions in Less CSS

How to Use Functions in Less CSS. Functions significantly streamline your programming experience, and this holds real when you're creating CSS code.

Free Movie Streaming Sites With No Sign Up Requirements

To enjoy a movie without the trouble, go here. Use these free, reputable, and registration-free websites.

How to Insert a Checkmark and Checkbox in PowerPoint

A simple checkmark or checkbox can grab your audience's attention. Here's how to add them to your PowerPoint presentation.

5 Ways That ChatGPT Is Already Being Used in the Wild

ChatGPT's AI powers boast plenty of real-world uses. Here are seven ways that the intelligent chatbot is already being used in the wild.