1

Why does this in x.prop2 returns Undefined but it works when trying to use it in x.prop3 through a method?

I have been told it's because of difference of scope between prop2 and prop3, but can anyone explain to me in detail the reason for that behavior?

let x = {
  prop1: 10,
  prop2: this.prop1,
  prop3: function () {
    return this.prop1
  }
};

console.log(x.prop2) // undefined
console.log(x.prop3()) // 10
ericmp
  • 1,163
  • 4
  • 18
WevDevNoob
  • 11
  • 1
  • The value of `this` is determined by how the **function** it appears within is called. (With some exceptions, notably arrow functions). – Quentin Jan 05 '23 at 16:50
  • The line `prop2: this.prop1` is within the global scope (not within a function). The line `return this.prop1` is within the scope of the anonymous function that was assigned to `prop3` which is invoked with `x` as `this` in the line `console.log(x.prop3())`. – CherryDT Jan 05 '23 at 16:51

0 Answers0