0

In my updateCamera(event) function, I am trying to access this.camera as can be shown in my constructor. Unfortunately, it's undefined in that function, I assume it's a scope issue, but I'm not sure how to solve it. Any ideas? Thank you.

export default class Experience {
    constructor(options = {}) {
        this.camera = new Camera();
        // removed unnecessary stuff
        this.onMouseDrag();
    }

    updateCamera(event) {
        console.log(this.camera); //Prints "undefined" in the console
        this.camera.position.x = (event.clientX / window.innerWidth) * 2 - 1;
    }

    onMouseDrag() {
        window.addEventListener("mousedown", () => {
            window.addEventListener("mousemove", this.updateCamera);
        });
        window.addEventListener("mouseup", () => {
            window.removeEventListener("mousemove", this.updateCamera);
        });
    }
awawawaw
  • 175
  • 3
  • 11
  • I suppose that before creating the clousure you could define a variable that points to to `this` and since it would be in the closure lexical scope you could access it, e.g. `const that = this`, and then do `that.updateCamera` inside the closure. – Edwin Dalorzo Dec 14 '21 at 02:48

1 Answers1

2

this behaves confusingly in class components.

When binding to a method (your event listener), this is not bound by default. To fix your issue, change this.updateCamera to this.updateCamera.bind(this) or use an anonymous function (()=>this.updateCamera()).

You can also bind this to your functions in your constructor to reduce confusion like this:

this.updateCamera = this.updateCamera.bind(this);
Elijah Mock
  • 587
  • 8
  • 21