this keyword in Javascript

this keyword is most important and confusing word for the javascript developer.
Compared to other languages like Java, javascript this is completely different.

Commonly this is referring to the current execution context in javascript.
In javascript, this is vary depending on how the function or method calls, not care about where the function or method is declared.
this is undefined when we are run the code in strict mode.

There are four different factors is changing or set the this(execution contextin javascript
  1. Global (Default binding)
  2. Object Method (Implicit binding)
  3. Call and apply method
  4. Bind method

Note: this is referring to lexical scope while using the fat arrow function.


Global

When calling a function like the below, this is referring to the window object in Javascript  and Global object in NodeJS. This is called default binding

function test(){
console.log(this)
}
test()

Object Method

In the object method, this is referring to the current object this is called implicit binding
let obj = { name:"Javascript",
version:"ES6",
get whoiam()
{
console.log(`This is ${this.name} version ${this.version}`)
}
}
 obj.whoiam // output is "This is Javascript version ES6"

Call and apply method

If we use to call and apply the method to call the function these two methods are taking the first argument as an execution context.
function explicitBind(par1){
  console.log(this.name,par1) // output is "Javsctipt Hi"
}
let obj={
  name:"Javsctipt",
  verison:"ES6"
}
explicitBind.call(obj,"Hi");
explicitBind.apply(obj,["Hi"]); 

The main difference between call and apply method is, the call is taking a string as an argument, apply is taking an array as an argument.

Bind method

The bind method is used to create a function with the context for later use. The bind method also takes the first argument as an execution context

function explicitBind(par1){
  console.log(`${this.name} ${par1}`)
}
let obj={
  name:"Javsctipt",
  verison:"ES6"
}
let newobj={
  name:"ReactJS",
  verison:"16"
}
let bindmethod = explicitBind.bind(obj,"test");
bindmethod(newobj) // The output is "Javsctipt test"

Related Articles

Comments