Home > Web Front-end > JS Tutorial > body text

A brief introduction to WeakMap in ES6

不言
Release: 2018-11-14 16:28:33
forward
1804 people have browsed it

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]])
Copy after login

Add

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

Delete

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

Contains

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

Weak reference feature

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

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template