Javascript 的 rhino 动态属性
在 Rhino 中,我可以通过在 Java 类上定义 js... 函数来添加特定属性。我想要的是定义一个包罗万象的函数,如果程序要引用尚未定义的属性,则该函数会被调用。有办法吗?
In Rhino, I can add specific properties by defining js... functions on a Java class. What I'd like is to define a catchall function that gets called if a program goes to reference a property that hasn't been otherwise defined. Is there a way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为没有办法使用本机语法来表达这个概念,甚至使用 Rhino/Spidermonkey 专有扩展(如 getters 和 setters): https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_Getters_and_Setters
但是,JavaScript 相当容易扩展,所以我认为你可以获得一些东西通过向 Object.prototype 添加一个方法来支持这种更高级样式的方法调用,效果非常接近。以下似乎可以满足您的要求:
打印以下内容:
I don't think there is a way to express this concept using native syntax, even using Rhino/Spidermonkey proprietary extensions like getters and setters: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_Getters_and_Setters
However, JavaScript is fairly easy to extend, and so I think you could get something pretty close by adding a method to Object.prototype to support this more advanced style method invocation. The following would seem to do what you want:
Which prints the following: