所以,我有以下代码:
this.balls = [];
function setup() {
createCanvas(800, 800);
noStroke();
balls.push(new Ball(width / 2, height / 2, 20))
}
function draw() {
for (var ball in this.balls) {
ball.drawCircle();
}
}
this.Ball = function(x, y, r) {
console.log("Ball created");
this.x = x;
this.y = y;
this.r = r;
this.drawCircle = function (){
ellipse(x, y, r);
}
}
问题是我收到以下错误:
Uncaught TypeError: ball.drawCircle is not a function
at draw (sketch.js:12)
at e.d.redraw (p5.min.js:6)
at e.<anonymous> (p5.min.js:4)
at e.<anonymous> (p5.min.js:4)
at new e (p5.min.js:5)
at e (p5.min.js:4)
所以它应该为balls数组中的每个球调用drawcircle函数,但是它说drawCircle不是一个函数。问题是我只是不明白为什么。我尝试使用var drawCircle而不是this.drawCirle,我也尝试使用funcion drawCircle。
亲切问候。
p.s. 这段代码使用 p5.js,执行 Ball 创建的日志
尝试使用类,这样您就不会遇到上下文this
问题:
function Ball(x, y, r) {
console.log("Ball created");
this.x = x;
this.y = y;
this.r = r;
}
Ball.prototype.drawCircle = function() {
ellipse(x, y, r);
};
或者在 ES6 中:
class Ball {
constructor(x, y, r) {
console.log("Ball created");
this.x = x;
this.y = y;
this.r = r;
}
drawCircle() {
ellipse(x, y, r);
}
}