Search code examples
javascriptoopgettersetter

Reinitialise the coordinate by using setter in Javascripts


I am new to OOP and just learning now. I want to reinitialise the default location of a circle by using the codes below:

function Circle(radius) {
  
  this.radius = radius;
  
  let defaultLocation = {
    x: 0,
    y: 0
  };

  this.getDefaultLocation = function(a, b) {
    return defaultLocation
  };
  
  Object.defineProperty(this, 'defaultLocation', {
    get: function(a, b) {
      return defaultLocation;
    },
    set: function(a, b) {
      defaultLocation = {
        x: a,
        y: b
      };
    }
  });

}

const circle = new Circle(10);

circle.defaultLocation = {
  x: 5,
  y: 6
};

However, i check in the chrome browser console, the result is:

x: {x: 5, y: 6}
y: undefined

Could you tell me where i done wrong and how to correct it? Thanks.


Solution

  • You can't pass two variables to set, but you can pass an object (or an array).

    class Circle {
    
      get defaultLocation() {
        return this._defaultLocation
      }
      
      set defaultLocation(loc) {
        this._defaultLocation = loc
      }
      
      constructor(radius) {
        this.radius = radius;
        this._defaultLocation = {
            x: 0,
            y: 0
        };
      }
    
    }
    
    const circle = new Circle(10);
    
    circle.defaultLocation = {
      x: 5,
      y: 6
    };