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?
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.