2016-03-27 13 views
0

どのように変数を関数として使用できますか?続き はJavaScriptのメンバー関数

$(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;を使用したい私のコードですが、コンソールにそれは引き分けが未定義であることを伝えます。どのように私は使用ball[i].draw(); // notice the parenthesis, to execute function.ball[i]

+0

マウスアップが起こる前に、どのようにボール配列にアクセスしますか? –

+0

はい、mouseUpの後に話しています。ボール配列はmouseUpでボールを取得しています。drawFunは一度実行されますが、forループでも実行されます。 –

+0

'this.draw = drawFun(this.px、this.px、this.rad、this.clr) ; 'は関数を作成していません。 'this.draw = function(){....}'のようなものが必要です。あるいは、drawFunが関数を返すようにするか、関数にしてください:this.draw = drawFun; – mplungjan

答えて

1

からdrawFunにアクセスし、これを使用することができます:あなたは、単にこのような場合であるdrawFun、によって返されるものを記憶している

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

function() { .. }がないとすると、定義されていません。

+0

ball [i] .draw()を使用します。 drawは関数ではないことを伝えるだけです –

+0

'this.draw = function(){...}'も使用してください@AnilKumar – mehulmpt

+0

準備関数の中でforループを動かす必要があります –

関連する問題