我正在使用 JavaScript 弱图,在 google chrome 开发者控制台中尝试此代码后,使用 --js-flags="--expose-gc" 运行,我不明白为什么弱图一直引用 ab 如果 a 是gc'ed。
var a = {listener: function(){ console.log('A') }}
a.b = {listener: function(){ console.log('B') }}
var map = new WeakMap()
map.set(a.b, [])
map.set(a, [a.b.listener])
console.log(map) // has both a and a.b
gc()
console.log(map) // still have both a and a.b
a = undefined
gc()
console.log(map) // only have a.b: why does still have a reference to a.b? Should'nt be erased?
Run Code Online (Sandbox Code Playgroud) 我想用DOM元素作为键创建一个哈希.这由以下代码说明:
var hash = {};
var set = function(element, value) { hash[element] = value; };
var get = function(element) { return hash[element]; };
set(document.getElementById('foo'), 'bar');
get(document.getElementById('foo')); // returns 'bar'
Run Code Online (Sandbox Code Playgroud)
如何确保哈希映射到每个哈希值的唯一值Element?
请注意,我不能将原始ID字符串用作键,因为Element可以传入任意字符串,包括那些没有id的字符串.
我正在阅读WeakMap的描述,它说:
在本机WeakMaps中,对关键对象的引用保持"弱",这意味着它们不会阻止垃圾收集,以防没有对该对象的其他引用.
通过阅读本文,我的理解是WeakMaps用于您试图利用JavaScript的垃圾收集的实例.从根本上我不明白的是我加粗的那条线.
为什么在普通的Map中,没有引用它们的对象不会被垃圾收集?这有什么好处,我是否必须从普通地图中明确删除?
javascript dictionary garbage-collection weakmap ecmascript-6
while (c) {
tag`str0 ${e} str1`
}
Run Code Online (Sandbox Code Playgroud)
JavaScript运行时创建一个冻结的数组,Object.freeze(['str0 ', ' str1'])但具有附加.raw属性.
是否可以将该对象用作a中的键,WeakMap以避免每次循环时都必须基于数组重做工作?
const memoTable = new WeakMap
function tag(templateStrings, ...values) {
let cached = memoTable.get(templateStrings)
if (!cached) {
// Compute cached and put it in the table for next time.
}
// Do something with cached and values
}
Run Code Online (Sandbox Code Playgroud)
第12.2.9.3节运行时语义:GetTemplateObject(templateLiteral)描述了如何缓存此值:
- 让领域成为当前的领域记录.
- 让templateRegistry成为领域.[[TemplateMap]].
所以从tag上面的循环中使用它应该是相同的,这将是一个很好的属性的密钥.
在我看来,[[TemplateMap]]必须弱引用模板对象数组,否则
for (let i = 0; i …Run Code Online (Sandbox Code Playgroud) javascript weakmap ecmascript-6 template-strings tagged-templates
我一直在阅读有关 WeakMap 的 MDN 文档。它提到了语法:
new WeakMap([iterable])
但是当我尝试这样做时,出现了错误:
var arr = [{a:1}];
var wm1 = new WeakMap(arr);
Run Code Online (Sandbox Code Playgroud)
未捕获的类型错误:用作弱映射键的值无效
您能为我提供一个有关如何通过数组执行此操作的示例吗?