码迷,mamicode.com
首页 > 其他好文 > 详细

[ES6] WeakMap vs Map

时间:2016-01-14 06:20:12      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

WeakMap: is a type of Map where only objects can be passed as keys. Primitive data type -- such are string, numbers, booleans, etc --- are not allowed.

 

let user = {};
let comment = {};

let mapSettings = new WeakMap();

mapSettings.set(user, "user");
maåSettings.set(comment, "comment");

console.log(mapSettings.set(user));
console.log(mapSettings.set(comment));

 

if:

mapSettings.set("title", "ES2015"); --> invalid value used as weap map key

 

Wekmap is not iterable, therefore, they can‘t be used with for...of.

 

WeakMaps are better with Memory:


let user = {}; // all objects occupy memory space

let userSatatus = new WeakMap();
userStatus.set(user, "logged"); // Objecct reference passed as key to the WeakMap

//...
someOtherFunction( user );
// Once it returns, user object can be garbage collected

Weakmaps don‘t prevent the garbage colector from collecting objects currently used as keys, but that are no longer referenced anywhere else in the system.

 

[ES6] WeakMap vs Map

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5129041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!