Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

ecmascript 6 - JavaScript weak maps - shouldn't it be showing empty?

As I understand it, with JavaScript weak maps, when an object used as a key has no remaining references to it, it is garbage collected (or at least slated for garbage collection) and removed from the weak map.

Quoting from javascript.info (emphasis mine):

If we use an object as the key in [the weak map], and there are no other references to that object – it will be removed from memory (and from the map) automatically.

However, if I run:

const mymap = new WeakMap();
let myobj = {foo: 'bar'};
mymap.set(myobj, 'etc');
myobj = null;
console.log(mymap);
setTimeout(() => console.log(mymap), 1000); //in case garbage collection is delayed

...when inspected in the console, it still shows the single entry I inserted into it.

enter image description here

Now, I realise there's no programmatical way to retrieve this entry, since I no longer have a reference to the object (and weak maps are not enumerable). But why would I believe it's been removed from the map if the console's still showing it's in there?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...