从全局范围调用嵌套函数

时间:2018-05-31 15:40:41

标签: javascript typeerror p5.js nested-function

所以,我有以下代码:

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)

因此它应该为ball数组中的每个球调用drawcircle函数,但是它表示drawCircle不是函数。问题是我只是不明白为什么。我曾尝试使用var drawCircle而不是this.drawCirle,我也尝试使用funcion drawCircle。

亲切的问候。

P.S。此代码使用p5.js,Ball创建日志执行

1 个答案:

答案 0 :(得分:0)

尝试使用课程,这样就不会遇到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);
  }
}