0

How do you make a class property that recalculates each time you use it?

class myClass {
  constructor(x, y) {
    this.x = x
    this.y = y
    this.percent = x/y * 100
  }
}

var test = new myClass(5, 10)

test.percent
//50

test.x = 10
test.percent
//still 50

I want test.percent to change 100 and adapt to other changes. Can I do this without turning the variable into a function?

3 Answers 3

4

What you are looking for is called a getter. A getter is recomputed everytime its property is accessed:

class myClass {
  constructor(x, y) {
    this.x = x
    this.y = y
  }

  get percent(){
    return this.x / this.y * 100
  }
}

var test = new myClass(5, 10)

console.log(test.percent) //50

test.x = 10
console.log(test.percent) //100

Sign up to request clarification or add additional context in comments.

Comments

1

There are two ways you can do this

  1. You can have this.percent as a function

class myClass {
  constructor(x, y) {
    this.x = x;
    this.y = y
    this.percent = function() {
      return this.x / this.y * 100
    }
  }
}
var test = new myClass(5, 10)

console.log(test.percent())
test.x = 10
console.log(test.percent())


  1. You can also use getter

class myClass {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  get percent() {
    return this.x / this.y * 100
  }
}

var test = new myClass(5, 10)

console.log(test.percent)
test.x = 10
console.log(test.percent)

Comments

1

You can use an accessor ( getter ) to alter the data each time you are accessing it.

In your case, you can replace the percent property by a getter.

class myClass {
  constructor(x, y) {
    this.x = x
    this.y = y
  }
  
  get percent() {
      return this.x / this.y * 100;
  }
}

var test = new myClass(5, 10)

console.log(test.percent);
//50

test.x = 10
console.log(test.percent);
//now 100

I have also edited your code to use this to access x and y

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.