【问题标题】:JS constructor class scope errorJS构造函数类范围错误
【发布时间】:2018-12-14 08:14:24
【问题描述】:
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

这里有什么问题?

【问题讨论】:

  • 这个错误没有发生,我测试了代码。你在哪里运行这个?
  • 我用的是sketch.js
  • 你在哪里写了"use strict";

标签: javascript class constructor


【解决方案1】:

错误信息说明了一切...您不能在设置之前声明变量。

您的问题也有解决方案。 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

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2011-11-20
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    相关资源
    最近更新 更多