Title: JavaScript this behavior inside an arrow function used in Object.defineProperty

29 Views Asked by At

Question:

I'm encountering unexpected behavior when using an arrow function as a getter in Object.defineProperty in JavaScript. Here's my code:

"use strict";

const obj = {
  a: 10,
};

Object.defineProperty(obj, "b", {
  get: () => {
    console.log(this.a, typeof this.a, this);
    return this.a + 10;
  },
});

When I try to access obj.b, the output is unexpected:

this.a is undefined typeof this.a is 'undefined' this refers to the global object (Window in a browser environment) I expected this to refer to the obj object. Can someone explain why this behavior occurs and how to achieve the desired behavior?

1

There are 1 best solutions below

0
moonwave99 On

In arrow functions, this retains the value of the enclosing lexical context's this. In other words, when evaluating an arrow function's body, the language does not create a new this binding. Source

Since your arrow function is defined in the global scope, it's bound to window.

If you use a regular function, it's going to be bound to the object.