DEV Community

Sabali
Sabali

Posted on

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.

Top comments (0)