首页 > 解决方案 > JavaScript 中的动态类属性

问题描述

你如何制作一个每次使用时都会重新计算的类属性?

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

我想test.percent改变100并适应其他变化。我可以在不将变量转换为函数的情况下执行此操作吗?

标签: javascript

解决方案


您要查找的内容称为getter. 每次访问其属性时都会重新计算 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) //100


推荐阅读