In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. More specifically an iterator is any object which implements the Iterator protocol by having a next() method which returns an object with two properties: value, the next value in the sequence; and done, which is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator's return value.
Once created, an iterator object can be iterated explicitly by repeatedly calling next(). Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to next() should simply continue to return {done: true}
const wm = new WeakMap();
class A {
constructor(number) {
wm.set(this, { number });
}
getNumber() {
return wm.get(this).number;
}
}
const a = new A(1);
console.log(a.getNumber());
Map
Map的使用主要就是围绕key跟value
所以说key可以是一个对象,一个字符串,或者说是一个Symbol
初始化一个 Map
需要介绍的方法(除get,has,clear忽略)
迭代器
简单来说一个迭代器创建之后,是通过next方法不断获取值,当返回的对象里done属性是true的时候代表这个迭代器已经执行完毕,而返回对象中的value则是当次迭代器返回的值
下面举出一个例子
需要不断的通过的获取下一个迭代器进行遍历
WeakMap
WeakMap 也是Map的一种,但是在方法和使用上又有一些不同
WeakMap的使用场景
一个比较有意思的使用场景,就是用来实现私有变量
附上一个介绍WeakMap比较详细的一个链接 https://zhuanlan.zhihu.com/p/25454328