Phoenixgyaan icon

TIL#1

this in traditional functions VS Arrow functions

alt text

function traditionalFunction() {
  //Your code here
}

const arrowFunction = () => {
  //Your code here
}

The this object/reference acts differently when used inside an traditional function and arrow function.
When referenced inside a traditional function, the this object refers to the value only within the scope of the function in which it is used.This means that a nested function will not be able to access the this object of the parent unless specified using tricks like 'that = this' or likewise.

function mainFunction() {
  this.newVar = 1
  console.log(this.newVar) // 1
  setTimeout(function() {
    this.newVar += 10
    console.log(this.newVar) // undefined
    // because it can't access 'this' from parent
  }, 1000)
}

BUT, in case of Arrow functions, the reference for this is obtained from it's surroundings.This means, if there is an arrow function initialized within another function, the this object of the parent function can be directly referenced using 'this.' in the child function.

function mainFunction() {
  this.newVar = 1
  console.log(this.newVar) // 1
  setTimeout(() => {
    // this is an anonymous arrow function
    this.newVar += 10
    console.log(this.newVar) // 11
    // because 'this' is refered from the surrounding
  }, 1000)
}