什么是避免对象命名空间冲突的 JavaScript 哈希表实现?
首先:我正在使用嵌入的相当晦涩的 javascript 实现作为 Adobe InDesign CS3 的脚本引擎。 这种实现有时与“标准”javascript 不同,因此是我的问题。
我正在使用 John Resig 的 jsdiff 库 (来源)来比较两个文档之间的文本选择。 jsdiff 使用普通对象作为关联数组将文本中的单词映射到另一个对象。 (请参阅 jsdiff.js 中第 129 行左右的“ns”和“os”变量。)
当文本中出现“reflect”一词时,我就开始头痛。 “reflect”是所有对象的默认只读属性。 当 jsdiff 尝试将关联数组上的值分配给 ns['reflect'] 时,一切都会爆炸。
我的问题:有办法解决这个问题吗? 有没有一种方法可以在 javascript 中创建哈希表而不使用明显的普通对象?
基本规则:切换脚本引擎不是一个选项。 :)
First off: I'm using a rather obscure implementation of javascript embedded as a scripting engine for Adobe InDesign CS3. This implementation sometimes diverges from "standard" javascript, hence my problem.
I'm using John Resig's jsdiff library (source here) to compare selections of text between two documents. jsdiff uses vanilla objects as associative arrays to map a word from the text to another object. (See the "ns" and "os" variables in jsdiff.js, around line 129.)
My headaches start when the word "reflect" comes up in the text. "reflect" is a default, read-only property on all objects. When jsdiff tries to assign a value on the associative array to ns['reflect'], everything explodes.
My question: is there a way around this? Is there a way to do a hash table in javascript without using the obvious vanilla object?
Ground rules: switching scripting engines isn't an option. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可能“问错了问题”(正如 Raymond Chen 所说); 不要试图避免使用普通对象,而是尝试更改关联数组成员的命名方式。
我尝试解决此问题的方法是:更改 jsdiff 构建数组的方式,而不是数组成员 ns["reflect"] ,以便该成员是 ns["_reflect"] 或其他一些变体。
You might be "asking the wrong question" (as Raymond Chen would say); rather than trying to avoid using the vanilla objects, try changing the way the associative array members are named.
The way I'd try to approach this: instead of there being an array member ns["reflect"], change the way that jsdiff builds the arrays so that the member is ns["_reflect"] or some other variation on that.
如果您使用的 JS 实现支持对象的 hasOwnProperty 方法,您可以使用它来测试是否已为对象显式设置属性或该属性是从其原型继承的。 例子:
If the JS implementation you're using supports the hasOwnProperty method for objects, you can use it to test whether a property has explicitly been set for an object or the property is inherited from its prototype. Example:
javascript 中给定的对象只是关联数组,实际上没有其他内置的哈希解决方案。 您也许可以通过将类包装在某些数组上来创建自己的伪哈希表,尽管涉及的手动工作可能会严重影响性能。
顺便说一句,我还没有真正使用或查看过 jsdiff 库,因此我无法根据提示或技巧提供任何有效的见解。
Well given objects in javascript are just associative arrays, there really isn't another built in solution for a hash. You might be able to create your own psuedo hashtable by wrapping a class around some arrays although there will probably be a significant performance hit with the manual work involved.
Just a side note I haven't really used or looked at the jsdiff library so I can't offer any valid insight as per tips or tricks.