DEV Community

Sabali
Sabali

Posted on

4 3

Understanding "this" in javascript

Simply put "this" in javascript refers to the object itself, for example

const myProfile = {
name:"Sabali",
sayHi:function(){
 console.log("Hi there, " + this.name)
  }
}

myProfile.sayHi() // "Hi there, Sabali"
Enter fullscreen mode Exit fullscreen mode

Javascript is notoriously known for performing behaviors not expected by the developer . One of those unexpected behaviors comes from using the "this" key word by calling it through a reference. Here's a demonstration

let greeting = myProfile.sayHi()
greeting() // "Hi there, undefined"
Enter fullscreen mode Exit fullscreen mode

The result is undefined reason being when calling a method through a reference, the method loses knowledge of what the original "this" was, in this case this becomes a global object.
In order to use this in an a reference we can employ the bind method.

Calling:

myProfile.greeting.bind(myProfile)
Enter fullscreen mode Exit fullscreen mode

This creates a new function where this is bound to point to Sabali, independent of where and how the method is being called.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay