0

I am having some trouble wrapping my head around some scope problems. I am using a class method to draw a square on the canvas and would like to move it around using another class method, but it seems I can't pass along the context...

class User {
  constructor(user, x, y, ctx) {
    for (let metric in user) { this[metric] = user[metric]; }
    this.initialX = x;
    this.initialY = y;
    this.x = x;
    this.y = y;
    this.ctx = ctx;
    this.draw(this.initialX, this.initialY, this.ctx);
   }

  draw(x, y, ctx) {
    ctx.fillStyle = 'white';
    ctx.fillRect(x,y,20,20);
  }

  move(e) {
    //// stuff about motion goes here
     console.log(e.key, this.ctx); //// can't access `ctx` - the user key shows up in the console but the context is nowhere to be seen
     //// eventually this needs to be draw(x, y, ctx) that's passed back up to the draw function
  }

}

The context is passed into the User class further down in the code as shown in this pen but as far as I can tell the way it's being passed to the User class isn't a problem, it's the way I'm accessing it in the move function.

I did also try defining a variable for the context in the constructor function independent of this but that wasn't successful either.

2 Answers 2

3

You must bind your method. ES6 classes doesn't do that automatically.

In your constructor try to add this line:

this.move = this.move.bind(this);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh great, this is exactly what I was looking for. Thank you so much!
1

You are expecting four arguments (e, x, y, ctx) into your event listener function but the listener will receive only one argument, the event.

Your have to explicitly pass all the arguments to your handler in order to use them or figure out another way to access them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.