2016-03-27 28 views
0

Bir değişkeni nasıl işlev olarak kullanabiliriz. Takip Javascript'te Üye İşlev

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

      } 

Şimdi ben ball[i].draw; kullanmak istiyorum benim kod ama konsolda bu beraberlik tanımsız olduğunu söyler. Nasıl Kullanım ball[i].draw(); // notice the parenthesis, to execute function.ball[i]

+0

Fare hareketi gerçekleşmeden önce, bu dizi dizisine nasıl erişeceksiniz? –

+0

Evet, mouseUp'tan sonra bahsediyorum. Toplar dizisi, mouseUp içinde toplanıyor ve drawFun bir kez yürütüyor ama ben de idam için çalıştırılmasını istiyorum –

+0

'this.draw = drawFun (this.px, this.py, this.rad, this.clr) ; 'bir işlev oluşturmuyor. This.draw = function() {....} 'gibi bir şeye ihtiyacınız var ya da drawFun bir işlev döndürüyor ya da işlevi olabilir: this.draw = drawFun; – mplungjan

cevap

1

den drawFun erişmek Ve bu kullanabilirsiniz: sadece bu böyledir drawFun, tarafından döndürülen ne depolamak olan

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

function() { .. } olmadan tanımlanmamıştır.

+0

topu kullanarak [i] .draw(); sadece çizmenin bir fonksiyon olmadığını söyler –

+0

@ this.draw = function() {...} 'da @AnilKumar – mehulmpt

+0

kullanın. For döngüsü de hazır fonksiyonun içinde hareket ettirmeniz gerekir –

İlgili konular