使用数组表示法了解何时将属性设置为对象
我有一个用作哈希表的对象,用于在 javascript 中存储键值对:
Storage["key"] = "value".
我发现我们可以使用 DefineSetter 为每个键设置设置器,但是,我们需要事先知道所有键名称。每当以这种方式设置值时,是否有办法执行某些操作?
例如,在执行以下操作时:
Storage["key"] = "value";
我希望它由自定义方法处理,例如:
customMethod : function(aKey, aValue) {
//do something with these two params
// inform somebody else about this.
}
想法/建议?
I have an object that is used as a hash table to store key value pairs in javascript:
Storage["key"] = "value".
I've found we can use defineSetter to have setters for each key, however, we need to know all key names beforehand. Is there a way of doing something whenever a value is set this way?
So for example, when doing:
Storage["key"] = "value";
I want it to be handled by a custom method like:
customMethod : function(aKey, aValue) {
//do something with these two params
// inform somebody else about this.
}
Thoughts/Suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,目前没有办法捕获所有属性分配。 Firefox 4 引入了一个实验性的 JavaScript Proxy API,它允许您执行此操作(让代理将所有调用转发到内部对象,但在设置属性时也会触发一些额外的操作)但这里可能有点矫枉过正 - 即使这个 API 是稳定的并且在其他浏览器中实现了。
No, there isn't currently a way to catch all property assignments. Firefox 4 introduced an experimental JavaScript Proxy API which would allow you to do this (have a proxy forward all calls to an inner object but also trigger some additional action when properties are set) but it would probably be an overkill here - even if this API were stable and implemented in other browsers.
您可以覆盖对象的
__defineSetter__
以获得更精细的控制。警告:不适用于所有浏览器!有关更多详细信息,请参阅此帖子:John Resig:JavaScript Getters 和 Setters
You can override
__defineSetter__
of the object to gain finer control. Caveat: Won't work in all browsers!See this post for more details: John Resig: JavaScript Getters and Setters