TypeError: Cannot read property of instance

时间:2016-08-31 18:45:57

标签: actionscript-3 html5-canvas animate-cc

I'm trying to make eye following for cursor like this http://www.flashuser.net/eyes-following-mouse-cursor-as3 in Adobe Animate 2015

function getMousePos(canvasDom, mouseEvent) {
  var rect = canvasDom.getBoundingClientRect();
  return {
    x: mouseEvent.clientX - rect.left,
    y: mouseEvent.clientY - rect.top
  };
}

canvas.addEventListener("mousemove", function (e) {
    mousePos = getMousePos(this, e);

    var xx = mousePos.x - this.Reye.x;
    var yy = mousePos.y - this.Reye.y;
    var radiusR1 = Math.atan2(yy, xx);
    var degreeR1 = radiusR1 / (Math.PI / 180);
    this.Reye.rotation = degreeR1;

}, false);

but i have error in browser

TypeError: Cannot read property 'x' of undefined

and this code is working fine

this.addEventListener("click", fl_MouseClickHandler.bind(this));
function fl_MouseClickHandler(evt)
{
    var xx = stage.mouseX - this.Reye.x;
    var yy = stage.mouseY - this.Reye.y;
    var radiusR1 = Math.atan2(yy, xx);
    var degreeR1 = radiusR1 / (Math.PI / 180);
    this.Reye.rotation = degreeR1;
}

1 个答案:

答案 0 :(得分:1)

你的范围错了。

您将匿名函数添加为内联侦听器:

canvas.addEventListener("mousemove", function (e) {

这是不好的做法,因为你很难再次删除监听器。一个挥之不去的监听器会阻止对象被收集,并可能导致内存泄漏。

无论如何,匿名函数(闭包)的范围是全局对象。 this不会指向定义函数的范围。

在第二个示例中,绑定范围:

fl_MouseClickHandler.bind(this)

对于命名函数不应该是必需的。

注意:使用类型并为事件类型使用定义的常量,例如MouseEvent.CLICK "click" - 防止打字错误并允许代码完成。