⬅ Go back to: Private Properties

Getters / Setters

There are two kinds of object properties. The first kind is data properties. We already know how to work with them. All properties that we’ve been using until now were data properties. The second type of properties is something new. It’s accessor properties. They are essentially functions that execute on getting and setting a value, but look like regular properties to an external code.


Accessor properties are represented by getter and setter methods. In an object literal they are denoted by get and set.

Example of getter and setter.

    function Circle(radius) {
        
        this.radius = radius;

        let defaultLocation =  { x: 0, y: 0 };

        this.getDefaultLocation = function() {
           return defaultLocation;
        } 

        this.draw = function() {
           console.log('draw');
        }

        Object.defineProperty(this, 'defaultLocation', {
            // Getter
            get: function() {
               return defaultLocation; 
            },
            // Setter
            set: function(value) {
                if (!value.x || !value.y)
                    throw new Error ('Invalid location.');

                defaultLocation = value;
            }
        });
    }

    circle.draw();
    circle.defaultLocation.x = 5;
    console.log(circle.defaultLocation);