What is the WeakMap object?
- [Instructor] Now that we have learned about Map, how it works and its various methods, understanding the concept of WeakMaps should be fairly easy. WeakMaps are very similar to Maps with the biggest difference being that its keys are weak and can be garbage collected. What is garbage collection? As far as what you need to know for this course, garbage collection is a way of freeing up memory that has been allocated to objects that are no longer in use. The process of garbage collection is performed automatically in JavaScript. Now let's explore what sets WeakMap apart from Map. As mentioned, the most significant difference between WeakMap and Map is related to keys. When using a WeakMap, your keys must be objects. If you'll recall from the previous section, Map accepts any value as a key. With WeakMaps you cannot use primitive data types as keys. As a quick reminder, primitive data types include strings, numbers, booleans and more. Another major difference is the available methods on the WeakMap. The only methods that are available on a WeakMap are: set, get, has and delete. Because there are no iterator methods, in order to know if a key exists in your WeakMap, you'll have to know what the key is to access the value. When you're ready to start using WeakMap, you'll use the constructor new WeakMap to create a new WeakMap. Now that we have the foundations, let's review the methods that you'll be able to utilize with WeakMap.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。