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]

5
  • Before mouseup happen, how will you access that balls array? Commented Mar 27, 2016 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 Commented Mar 27, 2016 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; Commented Mar 27, 2016 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. Commented Mar 27, 2016 at 15:50
  • Likely a duplicate of stackoverflow.com/questions/504803/… but I will not use my hammer here Commented Mar 27, 2016 at 15:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

by using ball[i].draw(); it simply tells draw is not a function
Use the this.draw = function() { ... } as well @AnilKumar
You need to move the for loop inside the ready function as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.