Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
How to set new values to a class

I have a rectangle class and I want to use shift to assign new values to this.x and this.y by the shift amount. For example, the coordinates were assigned (5,5) r.shift(3,3) will make this.x and this.y (3,3). Currently, my code makes x and y new values, it doesn't reassign them. How would I go on to do so?

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)
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to use += instead of just = to increment this.x in your shift function.

e.g.:

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

Full modified example:

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!