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
推荐阅读
- xml - 如何在 PowerShell 中从不同的 xml 节点动态读取特定的 XML 属性
- c# - 我们如何在 C# 中为 BenchmarkDotNet 的 [Arguments] 标签传递动态参数?
- android - Webview错误variations_seed(没有这样的文件或目录)
- javascript - How to re-render a full page with tag in react-router-dom
- javascript - 为什么在我的 Rails 应用程序中再次呈现 HTML div(包含数据表)之前无法隐藏它?
- laravel - Laravel - 如何在模型和控制器中验证评分系统
- objective-c - 如何将 Objective-c 静态库添加到 Swift 框架中?
- android - Intent.ACTION_CALL 仅在 android 9 pie 中不起作用
- sqlite - 如何显示任一列的邮政编码?
- javascript - 我尝试用 Javascript 编写一个程序,使用“if else”语句找到三个数字中最大的一个