javascript - 当 JavaScript 属性更改时执行特殊逻辑

标签 javascript properties

我有以下 JavaScript 代码。我想在对象 sizeLogic 中的任何属性发生更改时执行一些逻辑。具体来说,当这些属性中的任何一个设置为 true 时,我想将所有其他属性更改为 false。

问题:我如何实现这一目标?我不确定这在 JavaScript 中是否可能,无需编写像 set_leftTop(x) 这样的方法,以便在方法中我们可以编写自定义逻辑。

var sizeLogic = {
     leftTop: true,
     leftBottom: false,
     rightTop: false,
     rightBottom: false
}

最佳答案

您可能会找到object.watch有用取决于您的浏览器支持矩阵。

来自 MDN:

Warning: Generally you should avoid using watch() and unwatch() when possible. These two methods are implemented only in Gecko, and they're intended primarily for debugging use. In addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window. You can usually use setters and getters or proxies instead

参见:Listening for variable changes in JavaScript or jQuery

关于javascript - 当 JavaScript 属性更改时执行特殊逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32485996/

相关文章:

c# - 有没有办法让属性设置其支持值?

java - Camel 属性-占位符 : Not able to configure `camel:sslContextParameters` with nested properties

powershell - 如何从包含 "Keys"和 "Values"文本的哈希表中检索所有键?

objective-c - 在自定义 getter/setter 方法中使用 NSKeyedArchiver/Unarchiver

javascript - D3 时区偏移量移至前一天

Javascript绘制动态线

javascript - 如何在按下提交按钮之前将用户输入的值存储到javascript变量中

vb.net - VB扩展属性,而不是扩展方法

javascript - 我如何通过另一个元素从 xml 获取特定值

php - 单击链接时播放声音