Classes and a strange property

Hi there,
From following chapter 20 on classes, I have run into a strange situation. Here is the code:

class Planet {
  constructor(name, radius) {
    this.name = name;
    this.radius = radius;
  }
  
  getSurfaceArea() {
    let surfaceArea = 4 * Math.PI * Math.pow(this.radius, 2);
    console.log(surfaceArea + " square km!");
    return surfaceArea;
  }
  
  set gravity(value) {
    console.log("setting value");
    this._gravity = value;
  }
  
  get gravity() {
    console.log("Getting value!");
    return this._gravity;
  }
}

console.log(earth.gravity); // 9.81
console.log(earth._gravity); // Also 9.81??

I have to say that I didn’t expect this result! It seems as though two identical properties were created. Perhaps by the setter? How did this happen!?

It’s been a while since I read chapter 20, but I’m pretty confident about what’s going on here. You’ve explicitly defined a pair of accessor methods, set gravity and get gravity, and you’ve implicitly defined the _gravity property by dynamically writing to it and reading from it in the accessor methods. In effect, _gravity is the backing storage for the gravity read-write property.

I don’t know where you are in your process of learning JavaScript, but it’s important to understand that objects (class instances) can create storage for arbitrary property names that you write in code. So, when you set this._gravity = value, you’re creating new storage (or properties that store data) on that object the first time you set it. Accessors, or getters and setters like get gravity, don’t create storage unless the code you write as the implementation causes some storage.

It seems as though two identical properties were created. Perhaps by the setter? How did this happen!?

Yes, the only extra utility that get gravity and set gravity have over plain _gravity is that you’re able to intercept access to the storage and print extra messages with console.log. If you were to pervasively use _gravity in your code when dealing with Planet instances, you wouldn’t be able to open the developer console in your browser and easily observe places where the gravity value was observed or modified.

1 Like