1

Let's say there is a Person:

const Person = function(fname, lname) {
    this.fname = fname;
    this.lname = lname;
};

And I want to extend its functionality with a "name" getter

Object.defineProperty(Person.prototype, 'name', {
  get: () => `${this.fname} ${this.lname}`
});

However, this does not work. The this in the getter is not the instance prototype on which it is called:

const p = new Person('Taylor', 'Swift');
p.name // "undefined undefined"

Rather it is the scope of the property definition:

fname = 'Someone';
lname = 'Else';
p.name // "Someone Else"
craigmichaelmartin
  • 4,403
  • 1
  • 16
  • 20

1 Answers1

2

In the process of writing this question, the answer was obvious. Still posting in case it helps someone else.

Getter properties are indeed bound to their host object.

The issue is that I was using an arrow function for the getter. The arrow function does not have its own this, instead using the this value of the enclosing execution context.

This means the binding done for getter properties has no effect.

For example:

const foo = () => this.document;
foo() // global document object
foo.call({document: 'na'}) // still global document object
const bar = foo.bind({document: 'na'});
bar(); // still global document object
craigmichaelmartin
  • 4,403
  • 1
  • 16
  • 20