2017-12-27 15 views
0

연습으로 나는 this tutorial을 거쳐 모든 것을 자체 클래스에 집어 넣은 버전을 만들려고했습니다. 그래서 자신 만의 추가 기능을 추가 할 수 있습니다. 문제는 어떤 의미로 보이지 않는 오류가 발생하고 있다는 것입니다. 나는 클래스에서 lastRender 변수를 제거 할 때 Uncaught TypeError: Cannot read property 'lastRender' of null at loop (game-loop.js:13)null ____의 속성을 읽을 수 없습니다.

class GameLoop { 
    constructor(player, canvas) { 
    // Set other variables 
    this.lastRender = 0; 
    window.requestAnimationFrame(this.loop); 
    } 

    loop(timestamp) { 
    let progress = timestamp - this.lastRender; // This is ln. 13 in the actual program 

    this.update(progress); 
    this.draw(); 

    this.lastRender = timestamp; 
    window.requestAnimationFrame(this.loop); 
    } 

    update(progress) { 
    // Update function 
    } 

    draw() { 
    // Draw function 
    } 

} 

는 또한, 나에게 그 오류를주는 중지 (모든 주석 물건이 내 말에 채워집니다하지만이 질문에 관련 보이지 않았다)하지만, 대신 Uncaught TypeError: Cannot read property 'update' of null at loop (game-loop.js:15)

+0

'GameLoop' 클래스에는'lastRender'가 정의되어 있지 않습니다. 정의되어 있는지 확인하십시오. –

+0

@Abdullah Khan 무슨 뜻인지 모르겠다. –

+0

'GameLoop' 클래스에서'lastRender' 란 무엇입니까? 'this.lastRender'라고 말하면 객체 속성 인'lastRender'를 참조합니다. –

답변

1

.bind()을 사용하여 this에 올바른 값을 지정해야합니다. 이 변경이에

window.requestAnimationFrame(this.loop); 

을 :

window.requestAnimationFrame(this.loop.bind(this)); 

당신이 this.loop로 수행하는 등의 콜백과 같은 방법을 전달하는 경우, this의 값은 방법 만 참조를 전달되지 않습니다. 따라서 window.requestAnimationFrame()loop()이라면 this이 메서드 내에서 올바른 값을 갖도록 호출하지 않으므로 this.anything을 사용할 때 나타나는 오류가 발생합니다.

+0

나는 이것을 이미 시도했지만 아무것도 바꾸지 않은 것 같아서 그것을 꺼냈다. –

+0

또한 bind를 사용하는 것과 사용하지 않는 것의 차이점은 무엇입니까? –

+0

@ZacharyElkins - 콜백으로 메서드를 전달하는 모든 곳에서 사용해야합니다 (최소한 두 곳의 window.requestAnimationFrame()을 보여줘야합니다.) 지금 내 대답에는 더 많은 설명이 있습니다 .. – jfriend00

관련 문제