【问题标题】:Member Function in JavascriptJavascript中的成员函数
【发布时间】: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


【解决方案1】:

使用ball[i].draw(); // notice the parenthesis, to execute function. 并使用这个:

this.draw = function() { drawFun(this.px, this.py, this.rad, this.clr); }

没有function() { .. },您只是存储drawFun返回的内容,这种情况是未定义的。

【讨论】:

  • 通过使用 ball[i].draw();它只是告诉 draw 不是一个函数
  • 使用this.draw = function() { ... } 以及@AnilKumar
  • 您还需要将 for 循环移动到 ready 函数中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多