JS构造函数类范围错误

时间:2018-07-05 18:59:14

标签: javascript class constructor

var bubbles;

function setup() {
  createCanvas(600, 400);
  bubbles = new Bubble();
}

function draw() {
  background(50);
  bubbles.displ();
  bubbles.mov();
}

class Bubble {

  constructor() {

    this.x = 200;
    this.y = 200;

  };

  displ() {
    noFill();
    stroke(255);
    strokeWeight(4);
    ellipse(this.x, this.y, 25, 25);
  };

  mov() {
    this.x = this.x + random(-1, 1);
    this.y = this.y + random(-1, 1);
  }
}

错误消息

14:未捕获的SyntaxError:在严格模式之外尚不支持块范围的声明(let,const,函数,类)

您只是尝试使用p5.js的str()函数吗?

如果是这样,您可能需要将其移动到草图的setup()函数中。有关更多详细信息,请参见here

这是怎么了?

1 个答案:

答案 0 :(得分:0)

错误消息说明了一切...不允许在设置之前声明变量。

对于您的问题也有解决方案。 1我已经重写了它,使其适合您的代码。

var s = function( sketch ) {

    var bubbles;

    function setup() {
      sketch.createCanvas(600,400);
      bubbles = new Bubble();
    }

    function draw() {
      sketch.background(50);
      sketch.bubbles.displ();
      sketch.bubbles.mov();
    }
};

var myp5 = new p5(s);

1来自错误消息中提到的github存储库:https://github.com/processing/p5.js/wiki/Global-and-instance-mode

相关问题