Setter和Getter错误

时间:2016-10-15 13:20:56

标签: javascript object

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);

它返回一个错误:newPoint.setPoint不是一个函数。不明白为什么你可以帮助我?试图处理setter和getter。

2 个答案:

答案 0 :(得分:4)

您遇到的主要问题是通过使用赋值运算符=来调用setter。

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);

您还可以使用Object.definePropertyObject.defineProperties的标准API,以便其他人查看代码时更容易理解。

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

或与ES6

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

答案 1 :(得分:0)

从我读过的内容 defineGetter defineSetter 不再使用了。你可以这样做:

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);

您可以详细了解如何使用Object.defineProperties here