Search code examples
javascriptoopgetter-setter

JavaScript Object defineProperties and max


I'm learning the basics of OOP in JavaScript and I'm having some issues with this example:

var Human = function (first, surname) {
    var x = {};
    Object.defineProperties(x, {
        first: {
            get: function () {
                return this.first;
            },
            set: function (value) {
                this.first = value;
            }
        },
        surname: {
            get: function () {
                return this.surname;
            },
            set: function (value) {
                this.surname = value;
            }
        }
    });
    return x;
};
var alex = new Human("Alex", "Corlette");
  1. This: console.log(alex); Outputs:

    { }

  2. And this: console.log(alex.first); Outputs:

    Uncaught RangeError: Maximum call stack size exceeded

Anyone got any idea what I'm doing wrong?


Solution

  • The problem is the scope. Since you are defining a property and in the getter and setter referencing to those same getters and setters.

    The example could be fixed by removing the this keyword.

    var Human = function (first, surname) {
      var x = {};
      Object.defineProperties(x, {
        first: {
            get: function () {
                return first;
            },
            set: function (value) {
                first = value;
            }
        },
        surname: {
            get: function () {
                return surname;
            },
            set: function (value) {
               surname = value;
            }
        }
      });
      return x;
    };
    var alex = new Human("Alex", "Corlette");