类实例变量的范围

时间:2019-04-10 11:29:28

标签: javascript

这里是代码

class Joystick {
  constructor(panel, panelContext, x, y, w, h) {
    this.panel = panel;
    this.pctx = panelContext;
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    alert(this.x); //returns proper x
    panel.addEventListener("touchstart", this.touchstart);

    this.output = {
      x: 0,
      y: 0
    };
    this.startX = 0;
    this.startY = 0;
    this.id = -1;
  }
  touchstart(evt) {
    var e = evt.touches;
    for (var a = 0; a < e.length; a++) {
      var x = e[a].clientX;
      var y = e[a].clientY;
      alert(x + ",,," + this.x + ",,," + this.w) // undefined is alerted.
      if (x > this.x && x < this.x + this.w && y > this.y && y < this.y + this.h) {
        this.startX = x;
        this.startY = y;
        this.id = e[a].identifier;
        alert(this.id);
        break;
      }
    }
  }
}

我已经在构造函数中定义了this.x,this.w,但是alert()警告this.x和this.w为未定义。 我以为范围会有问题,但我找不到任何错误。我该怎么解决?

0 个答案:

没有答案