【发布时间】:2016-07-14 22:36:17
【问题描述】:
我们如何将变量用作函数。 以下是我的代码
$(document).mouseup(function (evt) {
balls.push(new ball(mousePos["downX"],
mousePos["downY"],
5 + (Math.random() * 10), 0.9, randomColor()));
});
function ball(positionX, positionY, radius, color) {
this.px = positionX;
this.py = positionY;
this.rad = radius;
this.clr = color;
this.draw = drawFun(this.px, this.py, this.rad, this.clr);
}
function drawFun(x, y, r, c) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = c;
ctx.fill();
//stroke
ctx.lineWidth = r * 0.1;
ctx.strokeStyle = "#000000";
ctx.stroke();
}
for (var i = 0; i < balls.length; i++) {
//TODO: DRAW ALL BALLS
balls[i].draw;
}
现在我想使用ball[i].draw;,但在控制台中它告诉我draw 是未定义的。我如何从ball[i]访问drawFun
【问题讨论】:
-
在 mouseup 发生之前,你将如何访问那个 balls 数组?
-
是的,在 mouseUp 之后。 Balls 数组在 mouseUp 上得到球,drawFun 正在执行一次,但我希望它也能在 for 循环中执行
-
this.draw = drawFun(this.px, this.py, this.rad, this.clr);没有创建函数。你需要像this.draw = function() { ....}这样的东西,或者让drawFun返回一个函数或者成为函数:this.draw = drawFun; -
你可以试试
this.draw = drawFun。另一种方法是将draw(或drawFun)函数添加到ball的原型中。 -
可能是 stackoverflow.com/questions/504803/… 的副本,但我不会在这里使用我的锤子
标签: javascript jquery