从全局范围调用嵌套函数
Calling a nested function from global scope
所以,我有以下代码:
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 创建的日志被执行
尝试使用 class 这样您就不会遇到 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);
}
}
所以,我有以下代码:
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 创建的日志被执行
尝试使用 class 这样您就不会遇到 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);
}
}