How the following can be explained: if we comment first call to console.log, the set.[[Entries]].length
will be 1
, if one is not commented set.[[Entries]].length
= 0
;
Output: length = 0;
let mySet = new WeakSet(),
key = {};
mySet.add( key ); // add the object to the set
//console.log( mySet ); // uncommenting will change the [[Entries]].length
key = null; // delete key
console.log( mySet ); // [[Entries]].length: 0
Otput: length = 1
let mySet = new WeakSet(),
key = {};
mySet.add( key ); // add the object to the set
console.log( mySet ); // commenting will change the [[Entries]].length
key = null; // delete key
console.log( mySet ); // [[Entries]].length: 1
One more edition: if we add one more console.log( mySet )
in the 2nd case (to the end of script). [[Entries]].length
will be 0
.
One of commentors mentioned that it should be the garbage collector. But how it will behave in the real script? If I'll use one time calling the object (without second time) will it be deleted or not (after object will be setted to null
)?
This isn't strange at all, it's just the standard behaviour of weak collections. [[Entries]] is an internal slot, with very much implementation-dependent behaviour, and might not even exist in the actual implementation but just be shown in the debugger.
Once you overwrite the key
reference to the object, it can get garbage-collected and won't be held by the mySet
either. The custom behaviour of console.log
apparently creates another reference to the object (as you can still interact with it in the console) so it is not garbage-collected, and still shows up in the list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.