【问题标题】:Calling a nested function from global scope [duplicate]从全局范围调用嵌套函数[重复]
【发布时间】:2018-05-31 15:40:41
【问题描述】:

所以,我有以下代码:

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。

亲切的问候。

附言此代码使用p5.js,执行Ball创建的日志

【问题讨论】:

  • draw()是p5js添加的函数,每帧调用一次
  • 在循环中:for (var ball in this.balls)ball 是一个整数(索引),尝试for (var ball of this.balls) ,或者保留in 并将ball.drawCircle(); 替换为this.balls[ball].drawCircle();
  • 这与范围或上下文无关,它是语法错误for..in 而不是for..of

标签: javascript typeerror p5.js nested-function


【解决方案1】:

尝试使用一个类,这样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);
  }
}

【讨论】:

  • 这(除了 ES6 部分)在功能上不是做同样的事情吗?感觉这会有同样的问题。很高兴得到纠正。顺便说一句,我没有投反对票。
  • 第一个选项我仍然得到错误,但第二个完全有效!谢谢! (我还不能接受答案)
  • 是的,两者都做同样的事情。它只是语法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-26
  • 2014-01-07
  • 2011-07-10
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多