代码之家  ›  专栏  ›  技术社区  ›  J P

JavaScript:无法识别对象的方法;为什么不呢?

  •  1
  • J P  · 技术社区  · 7 年前

    我正在尝试创建一个可以跟随我的鼠标的化身。


    var angleToBe; this.angleToBe; 。所有内容都直接链接到构造函数。我没有任何问题,直到我找到了方法,特别是 turnToMouse 一我的语法如下所示:

    Avatar.prototype.turnToMouse = function() {
      if (this.canTurn) {
        this.spotX = this.body.position.x;
        this.spotY = this.body.position.y;
        this.spotY = this.spotY * -1 + height;
        this.body.angleToBe = Math.atan2(cursorX - this.spotX, cursorY - this.spotY);
        this.body.__dirtyRotation = true;
        this.body.__dirtyPosition = true;
        this.gun.__dirtyRotation = true;
        this.gun.__dirtyPosition = true;
        this.body.rotation.set(0, 0, avatarAngleToBe);
      }
      setTimeout(this.turnToMouse, time);
    };
    

    本质上,这个功能只是不断地将化身(及其枪)转向鼠标的方向。此函数将正常工作,因为它完全相同(除了 this

    我遇到的问题是,当我将此代码放入构造函数中时(这是 function Avatar() {} ):

    this.turnToMouse();
    

    turnToMouse()

    我错过什么了吗?

    PS:如果你想看看我现在的工作化身和对象化身代码, click this link in google chrome .

    1 回复  |  直到 7 年前
        1
  •  2
  •   Blixt    7 年前

    JavaScript有一个称为 hoisting 。这会导致一些语句被“提升”到范围的顶部。

    在您的特殊情况下 function Avatar(...) { ... } 已吊装 这样当你打电话时它就可以使用了 new Avatar(...) 如果不是这样的话,你的代码不会走那么远,因为 Avatar

    Avatar.prototype.turnToMouse 你打电话 新化身(…) 这意味着该方法在运行时还不存在!

    新化身(…) 之后 您已分配所有 Avatar.prototype


    另外,如果你没有在构造函数中调用该方法,那也没关系,因为原型中的属性甚至对于在分配之前创建的实例也是可用的,只是在执行过程中不可用,直到它们实际被分配。


    this 对您的 setTimeout 呼叫要解决这个问题,只需将其更改为:

    var avatar = this;
    setTimeout(function () { avatar.turnToMouse(); }, time);
    

    function binding/context