Joshiepillow
Joshiepillow

Reputation: 227

Dynamic Class Properties in JavaScript

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?

Upvotes: 0

Views: 77

Answers (3)

Nicolas
Nicolas

Reputation: 8650

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

Upvotes: 1

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

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

Upvotes: 4

Code Maniac
Code Maniac

Reputation: 37755

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)

Upvotes: 1

Related Questions