在使用 CreateJS 的 Adobe AnimateCC 中,我在第一帧上有一个名为 disclaimer_btn
的 mc ,第一帧上的MC称为discTxt
。我希望能够将鼠标悬停在disclaimer_btn
上并在 discTxt
中的框架标签上 gotoAndStop 。在第 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
。
我已阅读this SO post和 this one在这种情况下,这些解决方案对我不起作用。
我知道这是范围问题,我在这里做错了什么?
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");
}
最佳答案
这只是订单的问题。因为您必须将函数定义为 this
上的变量,所以函数定义不会“提升”。首先定义提升的函数,无论它们在代码中定义的顺序如何。
// Hoisted
function myFunction() {}
// Not hoisted
var myFunction = function() {}
this.myFunction = function() {}
在第二个示例中,定义了变量本身,但在您设置它的行之前它将为空。您可以通过将 addEventListener
移动到该行下方来修复此问题,以便在定义函数后调用它。
或者,更改为托管方法并绑定(bind)它:
btn.addEventListener("click", myFunction.bind(this));
function myFunction() {}
您还可以使用 on
,它是 addEventListener
的 CreateJS 函数替代品,它具有一些语法糖,例如作用域参数。
btn.on("click", myFunction, this);
最后,如果您确实使用 this
定义函数,请确保传递正确的值。在您的示例中,您在 this
上定义函数,但将其作为 this.discTxt
的属性传递。除非 this.discTxt
是另一个 MovieClip,并且该函数是在那里定义的,否则您将传递 null。
TLDR:
- 如果您将函数定义为
this
上的属性,则将其移至 `addEventListener - 或者更改它,以便使用
function myFunction()
定义该函数,并绑定(bind)它。
关于javascript - CreateJS 针对 mc 范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42603954/