2017-01-11 4 views
1

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

답변

2

오류는

for (vertex of this) { 

어디 선언되지 않은 변수 vertex를 사용 말한다 것입니다. 그것은

for (var vertex of this) { 

또는 let 또는 const해야합니다.

0
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 (var vertex of this) { 
    callback(vertex) 
    } 
    } 

addVertex(key) { 
    const newVertex = new Vertex(key) 
    this.vertexList[key] = newVertex 
    this.numVerticies++ 
    return newVertex 
    } 


} 



const g = new Graph() 

for (var i = 0; i < 6; i++) { 
    g.addVertex(i) 
} 


g.each((vert) => console.log(vert)) 

할 때 콘솔에, 발전기에 있지만 아무 것도 인쇄를 내 각각의 방법을 변경하는 시도가 있어야한다 var vertexvertex이기 때문에 아직 선언하지 않았다.