HelterSkelter HelterSkelter - 29 days ago 16
Javascript Question

An infinite loop caused because of two getters?

The following code executes an infinite loop (prints

getter1
once, and then
getter2
until stopped):

var person1 = {
_age: 42,
get age() {
console.log("getter1");
return this._age;
}
};

Object.defineProperty(person1, "_age", {
get: function() {
console.log("getter2");
return this._age;
}
});
console.log(person1.age); // true


What causes it? (Note: I'm aware to the fact that I declared two different getters).

Answer

It's not an infinite loop, but infinite recursion. You're return this._age inside a getter for _age, but accessing this._age implicitly calls the getter again.

Note that once you've defined a getter called _age the old value of _age (42) is overwritten. There is no property with the value 42 anymore. If you want to create a getter that returns the value of a property it can't be the getter for that same property, so name your getter something other than _age:

var person1 = {
    _age: 42,
    get age() {
      console.log("getter1");
      return this._age;
    }
};

Object.defineProperty(person1, "age2", {
    get: function() {
      console.log("getter2");
      return this._age;
  }
});
console.log(person1.age); // 42
console.log(person1.age2); // 42
Comments