class MyCollection {
constructor() {
// 使用元编程定义一个隐藏属性,存储数据
Object.defineProperty(this, '_data', {
value: [],
writable: true,
enumerable: false,
configurable: true
});
}
add(element) {
this._data.push(element);
}
[Symbol.iterator]() {
let index = 0;
const data = this._data;
return {
next() {
if (index < data.length) {
return { value: data[index++], done: false };
} else {
return { done: true };
}
}
};
}
}
// 解释:
// 1. constructor 构造函数中,使用 Object.defineProperty 定义了一个隐藏属性 _data,
// 这个属性用于存储类实例中的元素,设置 enumerable 为 false 使得该属性在 for...in 或 Object.keys 等操作中不可见。
// 2. add 方法用于向 _data 数组中添加元素。
// 3. [Symbol.iterator] 方法实现了可迭代接口,返回一个迭代器对象。
// 迭代器对象有一个 next 方法,每次调用 next 方法,会返回数组 _data 中的下一个元素,
// 当所有元素都被遍历完后,返回 { done: true } 表示遍历结束。