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
}
}