简体   繁体   English

Javascript中的成员函数

[英]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; 现在我想使用ball[i].draw; but in console it tells that draw is undefined. 但是在控制台中,它告诉我们绘制未定义。 How can i access drawFun from ball[i] 我如何从ball[i]访问drawFun ball[i]

Use ball[i].draw(); // notice the parenthesis, to execute function. 使用ball[i].draw(); // notice the parenthesis, to execute function. 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. 没有function() { .. }您只是存储drawFun返回的内容,这种情况是不确定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM