javascript - JavaScript 中的动态类属性

标签 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 并适应其他更改。 我可以在不将变量转换为函数的情况下完成此操作吗?

最佳答案

您正在寻找的东西称为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

关于javascript - JavaScript 中的动态类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58715687/

相关文章:

javascript - 如何从我的 HTML 中获取 "activate/trigger"联系表单脚本?

javascript - 如果选中其他具有相同值的复选框,则检查复选框 jquery

javascript - jQuery 代码片段不适用于页面加载

javascript - react-redux useSelector hook 不允许将 props 直接传递给选择器

javascript - 在启用视差的页面中无法单击 anchor 链接

javascript - 最轻的 js/css 向用户提供 SPA 正在加载/初始化的视觉反馈

javascript - 如何在 PhysicsJS 中设置交互式和非交互式对象?

javascript - document.getElementsByName 在 IE11 中不起作用,但在 IE8 中运行良好?

javascript - 主干同步回调总是使用错误

javascript - 加载页面上的 CSS3 过渡