代码之家  ›  专栏  ›  技术社区  ›  Domo

如何为类设置新值

  •  -1
  • Domo  · 技术社区  · 3 年前

    我有一个rectangle类,我想使用shift为这个类指定新的值。x和这个。按移位量计算。例如,坐标被指定为(5,5)r。shift(3,3)将使其成为。x和这个。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)
    }
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   Wyck    3 年前

    你需要使用 += 而不仅仅是 = 增加 this.x 在你的 shift 作用

    例如。:

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