简体   繁体   中英

Javascript calling method in same class comes undefined?

So I'm relatively new to js and I'm trying to call a method 'lerp' inside my 'recordInputs' class. The recordInputs class is called somewhere else and works fine without the lerp function. The problem is that when the playerImage.x/y is equal to the lerp function a console error appears and says the 'lerp' method is undefined...

Here is the code:

class PlayerMoveClass {

  lerp(start, end, time) {
    return (1-time) * start + time * end;
  }

  RecordInputs(event) {
    currentXPos = playerImage.x;
    currentYPos = playerImage.y;

    xMousePosition = event.clientX;
    yMousePosition = event.clientY;

    playerImage.x = lerp(currentXPos, xMousePosition, 0.1);
    playerImage.y = lerp(currentYPos, yMousePosition, 0.1);
    console.log("X POS: " + playerImage.x + " Y POS: " + playerImage.y);
  }
}

Thanks in advance to anyone who can help!

Referencing class members requires the use of the this keyword.

In your case:

playerImage.x = this.lerp(currentXPos, xMousePosition, 0.1);
playerImage.y = this.lerp(currentYPos, yMousePosition, 0.1);

If you are using RecordInputs as an event listener (as suggested in the comments), you may also need to add this constructor to your class to bind this correctly:

constructor() {
    this.RecordInputs = this.RecordInputs.bind(this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM