Anil Kumar
Anil Kumar

Reputation: 21

Member Function in Javascript

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]

Upvotes: 0

Views: 64

Answers (1)

mehulmpt
mehulmpt

Reputation: 16587

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.

Upvotes: 1

Related Questions