调用对象函数时的问题:在线编辑器 p5.js 中的 "Script error. (: line 0)"
Issues when calling object function: "Script error. (: line 0)" in p5.js online editor
我认为这段简单代码的语法没有任何问题。但是只要我在draw
函数中调用generator.display();
,就会弹出错误信息:"Script error. (: line 0)"。
您可以在此处查看和 运行 代码:https://editor.p5js.org/huskyspeaks/sketches/-dN7ZQ9pg
您可能会发现(假设在线编辑器没有问题),删除 generator.display();
将消除错误。但是我真的不明白为什么会这样。我看不出这个简单框架的编码方式有什么问题。
var generator;
function setup() {
createCanvas(400, 640);
generator = new Generator(width / 2, height / 2, 4);
}
function draw() {
background(55);
generator.display();
}
var Generator = function(x, y, m) {
this.pos = createVector(x, y);
this.mass = m;
this.display = function() {
ellipse(pos.x, pos.y, 10 * mass, 10 * mass);
}
}
如果代码确实有问题,我该如何更新它?
您缺少对 this
的引用。
ellipse(this.pos.x, this.pos.y, 10 * this.mass, 10 * this.mass);
您在 this
上创建了 pos
和 mass
,但没有引用它。将其更改为如上所示修复它。
我认为这段简单代码的语法没有任何问题。但是只要我在draw
函数中调用generator.display();
,就会弹出错误信息:"Script error. (: line 0)"。
您可以在此处查看和 运行 代码:https://editor.p5js.org/huskyspeaks/sketches/-dN7ZQ9pg
您可能会发现(假设在线编辑器没有问题),删除 generator.display();
将消除错误。但是我真的不明白为什么会这样。我看不出这个简单框架的编码方式有什么问题。
var generator;
function setup() {
createCanvas(400, 640);
generator = new Generator(width / 2, height / 2, 4);
}
function draw() {
background(55);
generator.display();
}
var Generator = function(x, y, m) {
this.pos = createVector(x, y);
this.mass = m;
this.display = function() {
ellipse(pos.x, pos.y, 10 * mass, 10 * mass);
}
}
如果代码确实有问题,我该如何更新它?
您缺少对 this
的引用。
ellipse(this.pos.x, this.pos.y, 10 * this.mass, 10 * this.mass);
您在 this
上创建了 pos
和 mass
,但没有引用它。将其更改为如上所示修复它。