Тома Томов
Тома Томов

Reputation: 51

Setter and Getter error

function Point () {
    this.xPos = 0;
    this.yPos = 0;
}

Object.__defineGetter__.call(Point.prototype, "getPoint", function(){
    return "X: " + this.xPos + " Y: " + this.yPos;
});

Object.__defineSetter__.call(Point.prototype, "setPoint", function(point){
    var parts = point.toString().split(', ');
    parts[0] = this.xPos;
    parts[1] = this.yPos;
});

var newPoint = new Point();

newPoint.setPoint("44.5, 60.6");

console.log(newPoint.getPoint);

It returns me an error : newPoint.setPoint is not a function. Dont get it why can you help me ? Trying to handle the setter and getter.

Upvotes: 2

Views: 159

Answers (2)

Tyler
Tyler

Reputation: 90

From what i've read defineGetter and defineSetter aren't used much anymore. You could do something like this:

function Point() {
  this.xPos = 0;
  this.yPos = 0;
}

Object.defineProperties(Point, {
  xPos: {
    set: function(newValue) {
      this.xPos = newValue;
    },

    get: function() {
      return this.xPos;
    }
  },

  yPos: {
    set: function(newValue) {
      this.yPos = newValue;
    },

    get: function() {
      return this.yPos;
    }
  }
});

newPoint = new Point();
console.log(newPoint.xPos);
newPoint.xPos = 45;
console.log(newPoint.xPos);

You can read more about using Object.defineProperties here.

Upvotes: 0

synthet1c
synthet1c

Reputation: 6282

The main problem you are having is that setters are called by using the assignment operator = on it.

newPoint.setPoint = "44.5, 60.6";

function Point () {
    this.xPos = 0;
    this.yPos = 0;
}

Object.__defineGetter__.call(Point.prototype, "getPoint", function(){
    return "X: " + this.xPos + " Y: " + this.yPos;
});

Object.__defineSetter__.call(Point.prototype, "setPoint", function(point){
    var parts = point.toString().split(', ');
    // the assignment to this.xPos and this.yPos was the wrong way around
    this.xPos = parts[0];
    this.yPos = parts[1];
});

var newPoint = new Point();

// a setter is called by assigning a value to it
newPoint.setPoint = "44.5, 60.6";

console.log(newPoint.getPoint);

You could also use the standard api of Object.defineProperty or Object.defineProperties that will be easier to follow for anyone else looking at the code.

Object.defineProperty(Point.prototype, "getPoint", {
  get: function(){
    return "X: " + this.xPos + " Y: " + this.yPos;
  },
  set: function() {
    // stuff
  }
});

or with ES6

class Point {
  constructor() {
     this.xPos = 0
     this.yPos = 0
  }
  get getPoint() {
      // stuff
  }
  set setPoint() {
     // stuff
  }
}

Upvotes: 5

Related Questions