【问题标题】:Javascript calling method in same class comes undefined?同一类中的 Javascript 调用方法未定义?
【发布时间】:2018-11-14 16:47:59
【问题描述】:

所以我对 js 比较陌生,我试图在我的“recordInputs”类中调用一个方法“lerp”。 recordInputs 类在其他地方被调用,并且在没有 lerp 函数的情况下可以正常工作。问题是当 playerImage.x/y 等于 lerp 函数时,会出现控制台错误并说“lerp”方法未定义...

代码如下:

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

提前感谢任何可以提供帮助的人!

【问题讨论】:

  • 我猜RecordInputs 在某处作为事件侦听器附加,在这种情况下,您的代码将无法工作。请提供该代码。
  • 您需要将其称为this.lerp
  • 调用方法时可能使用this.lerp()?
  • 需要说明如何使用RecordInputs。调用上下文在这里很重要

标签: javascript class methods undefined


【解决方案1】:

引用类成员需要使用this 关键字。

在你的情况下:

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

如果您使用 RecordInputs 作为事件侦听器(如 cmets 中所建议的那样),您可能还需要将此构造函数添加到您的类中以正确绑定 this

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

【讨论】:

  • 基于参数event 的上下文很可能是错误的,可能来自 dom 事件侦听器
  • 是的,你是对的,谢谢!是的,它也用作事件侦听器,添加了构造函数并像魅力一样工作!
猜你喜欢
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 2020-10-05
  • 1970-01-01
相关资源
最近更新 更多