-2

I presume that objects added to a WeakSet and/or WeakMap are themselves tagged in some way to indicate membership. If so, is this tagging visible in userland code?

For example:

const go = () => {
  const o = {}
  s.add(o)
  return o
}
const s = new WeakSet
const o = go()
// can I detect that `o` is in a WeakSet, just by inspecting `o`?
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    Please may you provide a code example to show your thinking? – evolutionxbox Jul 22 '22 at 14:58
  • This smells like a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Andreas Jul 22 '22 at 15:00
  • Not an XY problem: I actually want to know whether the object is detectibly changed. – Ben Aston Jul 22 '22 at 15:02
  • 1
    No, the object has not "visibly" changed. – trincot Jul 22 '22 at 15:02
  • What do you mean by changed? What are you expecting to be affected? – evolutionxbox Jul 22 '22 at 15:02
  • No, just from looking at `o` you cannot detect wheter it's part of a weakset (or any other data structure) or not – derpirscher Jul 22 '22 at 15:04
  • Why do you want to know if `o` is in a `WeakSet`/`WeakMap`? – Andreas Jul 22 '22 at 15:08
  • 1
    The [specification](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakset-objects) doesn't define anything like that: _"The data structure used in this specification is only intended **to describe the required observable semantics of WeakSets. It is not intended to be a viable implementation model.**"_ – Andreas Jul 22 '22 at 15:14
  • @Andreas This might be relevant to the "tagging" concept: ["This characteristic can be achieved by using an inverted per-object mapping of weak map instances to keys."](https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakmap-objects). I also note that the spec is explicitly not dictating an implementation, however. – Ben Aston Jul 22 '22 at 15:17
  • 1
    You can do anything you want if you're the owner of an actual implementation of the spec. But the spec on its own doesn't _define_ anything that would do what you're asking about... – Andreas Jul 22 '22 at 15:19

1 Answers1

1

No, this is not visible in userland code. You need access to the WeakMap/WeakSet instance itself to test for membership. This is used to emulate truly private properties in classes.

"Tagging" the contained objects at best is an implementation detail (and something like that was used in most polyfills), but they might also be implemented in any other way. The only thing on actual implementation in engines I could find is Sigurd Schneider's talk Inside V8: weak collections, ephemerons, and private fields.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375