[英]How do I make a property that updates itself automatically based on some other value(s)?
Suppose I have an object like this with some arbitrary values... 假设我有一个带有一些任意值的对象...
let object = {
value: 5,
min: 1,
max: 100,
valid: true
}
How could I make it so that the valid
property updates automatically if the value
property is not within the range? 如果
value
属性不在范围内,如何使valid
属性自动更新? I know I could have made a getter
in the object like this... 我知道我可以在这样的物体上
getter
...
get valid() {
if (this.value > this.max || this.value < this.min) {
return false
else {
return true
}
}
...but this only updates valid
when it is accessed. ...但这仅在访问时更新
valid
。 I need valid
to always be up to date based on the other values of the object. 我需要
valid
永远是最新的基于对象的其他值。
It's often that I eventually realize that my entire way of thinking about a problem was wrong. 通常,我最终意识到我对问题的整个思考方式是错误的。 Is this one of those cases?
这是其中一种吗? For example, I know that if I use
setter
functions for updating all three of the other objects I could use them to keep valid
up to date, but that seems like the wrong approach. 例如,我知道如果我使用
setter
函数来更新所有其他三个对象,则可以使用它们来保持valid
最新状态,但这似乎是错误的方法。
What should I do? 我该怎么办?
This is the only way I can think of doing it without getters. 这是我可以想到的没有吸气剂的唯一方法。 It updates the value of
valid
every time the other properties are updated. 每当其他属性更新时,它都会更新
valid
。
var obj = { val: 5, minimum: 1, maximum: 100, valid: true, set value(v) { this.val = v; this.updateValid(); }, set min(m) { this.minimum = m; this.updateValid(); }, set max(m) { this.maximum = m; this.updateValid(); }, updateValid : function() { this.valid = (this.val >= this.minimum && this.val <= this.maximum) } } obj.value = -1; console.log(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.