如何将新值设置为 class

How to set new values to a class

我有一个矩形 class,我想使用 shift 将新值按移位量分配给 this.x 和 this.y。例如,坐标分别赋值 (5,5) r.shift(3,3) 会使 this.x 和 this.y (3,3)。目前,我的代码使 x 和 y 成为新值,但不会重新分配它们。我将如何继续这样做?

class Rectangle {
  constructor(x, y, width, height){
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  }
}

Rectangle.prototype.shift = function (changeInX, changeInY) {
  this.x = changeInX
  this.y = changeInY
}
//returns value string
Rectangle.prototype.toString = function () {
  return 'x is ' + this.x + ', y is ' + this.y + ', width is ' + this.width + ', height is ' + this.height
}
//offsets coordinates by amount
Rectangle.prototype.offset = function (changeInX, changeInY) {
 return new Rectangle(this.x+changeInX, this.y+changeInY, this.width, this.height)
}

您需要使用 += 而不是 = 来增加 shift 函数中的 this.x

例如:

  this.x += changeInX
  this.y += changeInY

完整修改示例:

class Rectangle {
  constructor(x, y, width, height){
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  }
}

Rectangle.prototype.shift = function (changeInX, changeInY) {
  this.x += changeInX
  this.y += changeInY
}
//returns value string
Rectangle.prototype.toString = function () {
  return 'x is ' + this.x + ', y is ' + this.y + ', width is ' + this.width + ', height is ' + this.height
}
//offsets coordinates by amount
Rectangle.prototype.offset = function (changeInX, changeInY) {
 return new Rectangle(this.x+changeInX, this.y+changeInY, this.width, this.height)
}

const rect = new Rectangle(1, 2, 3, 4);
console.log('before:', rect.toString())
rect.shift(100, 200);
console.log('after:', rect.toString())