私はES6クラス内のイテレータを試していて、自分のクラスの各メソッドを作成するときに参照エラー:ReferenceError: vertex is not defined
を実行しています。頂点をグラフに追加することができ、グラフインスタンスが正しいデータで印刷します。このイテレーターの使用は正しいですか?ES6クラスメソッド内でイテレータを使用する方法
class Vertex {
constructor(key) {
this.id = key
this.connectedTo = {}
}
}
class Graph {
constructor() {
this.vertexList = {}
this.numVerticies = 0
}
[Symbol.iterator]() {
// Reflect.ownKeys() === Object.keys()
const vertexListKeys = Reflect.ownKeys(this.vertexList)
let index = 0
return {
next:() => {
// Reflect.get(myObj, key) === Object[key]
let value = Reflect.get(this.vertexList, vertexListKeys[index])
index++
return {
done: index > vertexListKeys.length ? true : false,
value: value
}
}
}
}
// Iterate through vertexList values
each(callback) {
for (vertex of this) {
callback(vertex)
}
}
addVertex(key) {
const newVertex = new Vertex(key)
this.vertexList[key] = newVertex
this.numVerticies++
return newVertex
}
}
const graph = new Graph()
for (var i = 0; i < 6; i++) {
g.addVertex(i)
}
graph.each((vert) => console.log(vert))
// ReferenceError: vertex is not defined
// for (vertex of this) {
// ^
私も、私は、各機能ではそう
*each(callback) {
for(vertex in this) {
yield callback(vertex) // omitting yield doesn't work either
}
}