0

在使用 CreateJS 的 Adob​​e AnimateCC 中,我在第一帧上有一个 mc,在第一帧上有一个disclaimer_btnmc discTxt。我希望能够将鼠标悬停disclaimer_btn和 gotoAndStop 放在discTxt. 在第 150 帧左右,我尝试将鼠标悬停,但它不起作用。如果我在我的函数中使用警告框,那就可以了。

错误是Uncaught TypeError: Cannot read property 'bind' of undefined并且在它指向的代码中.bind(this));

如果我在收到错误this.discTxt之前删除。this.discTxt.fl_MouseOverHandler.bind(this));Uncaught ReferenceError: fl_MouseOverHandler is not defined

我已经阅读了这篇 SO 帖子,并且在这种情况下,这些解决方案对我不起作用。

我知道这是范围的问题,我在这里做错了什么?

var frequency = 3;
stage.enableMouseOver(frequency);
this.disclaimer_btn.addEventListener("mouseover", this.discTxt.fl_MouseOverHandler.bind(this));

this.fl_MouseOverHandler = function()
{
    this.discTxt.gotoAndStop("on");

}
4

1 回答 1

1

这只是订单的问题。因为您必须将函数定义为 on 上的变量this,所以函数定义不是“提升”的。提升的函数首先被定义,无论它们在代码中定义的顺序如何。

// Hoisted
function myFunction() {}

// Not hoisted
var myFunction = function() {}
this.myFunction = function() {}

在第二个示例中,变量本身已定义,但在您设置它的那一行之前,它将为空。您可以通过将 移至该addEventListener行下方来解决此问题,以便在定义函数后调用它。

或者,更改为托管方法,并将其绑定:

btn.addEventListener("click", myFunction.bind(this));
function myFunction() {}

您还可以使用on,它是 CreateJS 函数的替代品addEventListener,它具有一些语法糖,例如范围参数。

btn.on("click", myFunction, this);

最后,如果您确实使用 定义了函数this,请确保您传递了正确的值。在您的示例中,您在 上定义函数this,但将其作为 的属性传递this.discTxt。除非this.discTxt是另一个 MovieClip,并且函数是在那里定义的,否则您将传递 null。

TLDR:

  • 如果将函数定义为 on 上的属性this,则将其移至 `addEventListener 下方
  • 或更改它,以便使用定义函数function myFunction()并绑定它。
于 2017-03-05T16:02:13.257 回答