1

Why can't I use a fat arrow function in Object.define()?

Minimal, Complete, and Verifiable Example

Works

class Car {
  constructor(color) {
    this.color = color;
  }
}
Object.defineProperty(Car.prototype, 'getColor', {
  value: function() { // <--- ******** HERE ***********************
    return this.color
  }
  , writable:false
  , configurable: true
  , enumerable: true
})
const redCar = new Car('red');

console.log(redCar.getColor()); //-> red

Broken

class Car {
  constructor(color) {
    this.color = color;
  }
}
Object.defineProperty(Car.prototype, 'getColor', {
  value: () => { // <--- DOES NOT WORK
    return this.color
  }
  , writable:false
  , configurable: true
  , enumerable: true
})
const redCar = new Car('red');

console.log(redCar.getColor()); //-> undefined
kmiklas
  • 11,204
  • 17
  • 55
  • 84
  • 3
    Unlike regular functions, `this` won't be bound to anything when calling an arrow function. – Pointy Apr 04 '18 at 17:07

0 Answers0