0

in code snippet below:

  • in 1st case with arrow function - object logged

  • in 2nd case with function declaration - window logged

how and why does the arrow function preserve the context?

// 1ST CASE
function A() {
  this.getThis = () => {
    console.log(this)
  }
}

const a = new A

const aa = a.getThis
/* same as:
    const aa = () => {
    console.log(this)
  }
*/

aa() // object, context preserved O_o

// 2ND CASE
function B() {
  this.getThis = function() {
    console.log(this)
  }
}

const b = new B

// b.getThis() // will log object

const bb = b.getThis
/* same as:
    const bb = function() {
    console.log(this)
  }
*/

bb() // window
  • 1
    "How" is an implementation detail of the specific JS engine. "Why" is because *that's the point of arrow functions* – Quentin Feb 09 '22 at 15:49

0 Answers0