Home  >  Article  >  Web Front-end  >  A brief introduction to WeakMap in ES6

A brief introduction to WeakMap in ES6

不言
不言forward
2018-11-14 16:28:331810browse

This article brings you a brief introduction to WeakMap in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Overview

WeakMap is similar to Map in use and similar to Set in features. Compared with Map, it has the following characteristics

Non-enumerable

The key of WeakMap can only be an object

WeakMap is a weak reference. If the key in WeakMap is not referenced, it will be recycled by the garbage collection mechanism

Initialization

new WeakMap([[{},1]])

Add

let weakmap=new WeakMap()
weakmap.add({},"1")
weakmap.add({num:1},()=>{})

Delete

let obj={}
let weakmap=new WeakMap()
weakmap.add(obj,"1")
weakmap.add({},"2")
weakmap.delete(obj) //true
weakmap.delete({}) //false

Contains

let obj={}
let weakmap=new WeakMap()
weakmap.add(obj,"1")
weakmap.has(obj)//true
weakmap.has({})//false

Weak reference feature

let weakmap=new WeakMap([[{},1]])
setTimeout(()=>{console.log(weakmap)},3000)
// 3s后输出一下内容,数据消失了
WeakMap {}

The above is the detailed content of A brief introduction to WeakMap in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete