简体   繁体   English

EcmaScript6:带有WeakSet参数的console.log的奇怪行为

[英]EcmaScript6: strange behavior of console.log with WeakSet argument

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 ; 如何解释以下内容:如果我们首先调用console.log,则set.[[Entries]].length将为1 ,如果没有注释set.[[Entries]].length = 0 ;

Output: length = 0; 输出:长度= 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 输出:长度= 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). 还有一个版本:如果我们在console.log( mySet )情况下添加一个console.log( mySet ) (到脚本的末尾)。 [[Entries]].length will be 0 . [[Entries]].length0

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 )? 如果我将使用一次调用该对象(没有第二次)它是否会被删除(在将对象设置为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. [[Entries]]是一个内部插槽,具有很多与实现相关的行为,甚至可能在实际实现中不存在,只是在调试器中显示。

Once you overwrite the key reference to the object, it can get garbage-collected and won't be held by the mySet either. 一旦覆盖对象的key引用,它就可以被垃圾收集,也不会被mySet 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. console.log的自定义行为显然会创建对该对象的另一个引用(因为您仍然可以在控制台中与它进行交互),因此它不会被垃圾收集,并且仍会显示在列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM