JavaScript 属性改变时执行特殊逻辑
Execute special logic when JavaScript property is changed
我在 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 中有以下代码。当对象 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