在JavaScript中捕获对未定义属性的访问权限 [英] Catch access to undefined property in JavaScript
问题描述
Spider-Monkey JavaScript引擎实现JavaScript对象的 __ noSuchMethod __
回调函数。
The Spider-Monkey JavaScript engine implements the __noSuchMethod__
callback function for JavaScript Objects.
此函数被调用每当JavaScript尝试执行Object的未定义方法时。
This function is called whenever JavaScript tries to execute an undefined method of an Object.
我想设置一个Object的回调函数,只要Object中的未定义属性被调用访问或分配给。
I would like to set a callback function to an Object that will be called whenever an undefined property in the Object is accessed or assigned to.
我还没有找到为JavaScript对象实现的 __ noSuchProperty __
函数,我很好奇有任何解决方法可以达到相同的结果。
I haven't found a __noSuchProperty__
function implemented for JavaScript Objects and I am curios if there is any workaround that will achieve the same result.
请考虑以下代码:
var a = {};
a.__defineGetter__("bla", function(){alert(1);return 2;});
alert(a.bla);
相当于 [alert(1); alert(2)]
- 即使a.bla未定义。
It is equivalent to [alert(1);alert(2)]
- even though a.bla is undefined.
我想获得相同的结果但是未知属性(即事先不知道a。bla将是访问的属性)
I would like to achieve the same result but to unknown properties (i.e. without knowing in advance that a."bla" will be the property accessed)
推荐答案
在ECMAScript的下一个版本中,它应该非常简单,使用Object.observe 。
在此处阅读更多内容:
http: //addyosmani.com/blog/a-few-new-things-coming-to-javascript/
In ECMAScript's next version it should be quite easy, using Object.observe. Read more here: http://addyosmani.com/blog/a-few-new-things-coming-to-javascript/
这篇关于在JavaScript中捕获对未定义属性的访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!