JavaScript 对象 ID
JavaScript 对象/变量是否有某种唯一标识符?就像 Ruby 有 object_id
一样。我指的不是 DOM id 属性,而是某种内存地址。
Do JavaScript objects/variables have some sort of unique identifier? Like Ruby has object_id
. I don't mean the DOM id attribute, but rather some sort of memory address of some kind.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我刚刚遇到这个问题,想补充一下我的想法。正如其他人所建议的那样,我建议手动添加 ID,但如果您确实想要与您所描述的内容接近的内容,您可以使用以下方法:
您可以通过调用
objectId(obj)
。然后,如果您希望 id 成为对象的属性,您可以扩展原型:或者您可以通过添加类似的函数作为方法来手动向每个对象添加 ID。
主要的警告是,这将防止垃圾收集器在对象超出范围时销毁它们...它们永远不会超出
allObjects
数组的范围,因此您可能会发现内存泄漏一个问题。如果您打算使用此方法,那么您应该仅出于调试目的而这样做。需要时,您可以执行objectId.clear()
来清除allObjects
并让 GC 完成其工作(但从那时起,对象 ID 将全部重置)。I've just come across this, and thought I'd add my thoughts. As others have suggested, I'd recommend manually adding IDs, but if you really want something close to what you've described, you could use this:
You can get any object's ID by calling
objectId(obj)
. Then if you want the id to be a property of the object, you can either extend the prototype:or you can manually add an ID to each object by adding a similar function as a method.
The major caveat is that this will prevent the garbage collector from destroying objects when they drop out of scope... they will never drop out of the scope of the
allObjects
array, so you might find memory leaks are an issue. If your set on using this method, you should do so for debugging purpose only. When needed, you can doobjectId.clear()
to clear theallObjects
and let the GC do its job (but from that point the object ids will all be reset).如果您想在不修改底层对象的情况下查找/关联具有唯一标识符的对象,您可以使用
WeakMap
:使用
WeakMap
而不是Map
确保对象仍然可以垃圾收集。If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a
WeakMap
:Using a
WeakMap
instead ofMap
ensures that the objects can still be garbage-collected.不,对象没有内置标识符,尽管您可以通过修改对象原型来添加标识符。下面是一个如何做到这一点的示例:
也就是说,一般来说,修改对象原型被认为是非常糟糕的做法。相反,我建议您根据需要手动为对象分配 id,或者按照其他人的建议使用
touch
函数。No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:
That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a
touch
function as others have suggested.实际上,您不需要修改
object
原型。以下应该能够足够有效地“获取”任何对象的唯一 ID。Actually, you don't need to modify the
object
prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.