0

How can we use a variable as a function. Following is my code

$(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;

            }

Now i want to use ball[i].draw; but in console it tells that draw is undefined. How can i access drawFun from ball[i]

Anil Kumar
  • 21
  • 1
  • 3
  • Before mouseup happen, how will you access that balls array? – Rajaprabhu Aravindasamy Mar 27 '16 at 15:47
  • Yes am talking about after the mouseUp. Balls array is getting balls in it on mouseUp and drawFun is executing once but i want it to be executed in for loop as well – Anil Kumar Mar 27 '16 at 15:49
  • `this.draw = drawFun(this.px, this.py, this.rad, this.clr);` is not creating a function. You need something like `this.draw = function() { ....}` or have drawFun return a function or be the function: this.draw = drawFun; – mplungjan Mar 27 '16 at 15:50
  • You can try `this.draw = drawFun`. An alternative would be to add the draw (or drawFun) function to the prototype of ball. – ConnorsFan Mar 27 '16 at 15:50
  • Likely a duplicate of http://stackoverflow.com/questions/504803/how-do-you-create-a-method-for-a-custom-object-in-javascript but I will not use my hammer here – mplungjan Mar 27 '16 at 15:56

1 Answers1

1

Use ball[i].draw(); // notice the parenthesis, to execute function. And use this:

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

Without function() { .. } you are simply storing what is returned by drawFun, which is this case is undefined.

mehulmpt
  • 15,861
  • 12
  • 48
  • 88