2014-03-05 45 views
2

我試圖通過一組點的像在水平或垂直方向功能不能訪問該對象在javascript

我使用的對象內部的功能,並試圖調用移動cicle的管內同一個對象的另一個功能。

var ParticleGen = function() { 
    this.pipeBegin = points[pipeIndex]; 
    this.pipeEnds = points[pipeIndex + 1]; 
    this.begin = function(){ 
     var pipeBegin = points[pipeIndex]; 
     var pipeEnds = points[pipeIndex + 1]; 
     nx = pipeBegin.x; 
     ny = pipeBegin.y; 
     if(pipeBegin.x == pipeEnds.x && pipeBegin.y >= pipeEnds.y){ 
      if(ny > pipeEnds.y) { 
       ctx.clearRect(0, 0, w, h); 
       drawCircle(nx, ny); 
       ny--; 
       nx = nx; 
      }else if(ny == pipeEnds.y){ 
       cancelAnimationFrame(animloop); 
       this.callBegin(); 
      } 
      requestAnimFrame(animloop); 
     } 
     animloop(); 
    } 
    this.callBegin = function(){ 
     if(pipeIndex <= 3){ 
      pipeIndex++; 
     } 
     this.begin(); 
    } 
}; 

但它會引發錯誤。

Uncaught TypeError: Object [object global] has no method 'callBegin' 

的代碼片斷可以看出here

謝謝

+0

哪裏是你的callBegin()函數? –

回答

0

您打電話的功能this.callBegin不是您認爲的功能:當您撥打電話時(第63和78行),您在另一功能(animloopanimloop1等)內。在這些函數中,the scope is changedthis關鍵字指的是函數animloop(不是ParticleGenwindow)。 animloop沒有財產callBegin(功能或其他)。

你應該先 '救' 了ParticleGen範圍的子功能中使用它:

var ParticleGen = function() { 

    var pg = this; 

    // etc 

    function animloop() { 

     // etc 

     pg.callBegin(); 

    } 
} 

的更新,工作小提琴:http://jsfiddle.net/PZCpf/2/

+0

謝謝。它的工作.. 但不是像我想... 更新的小提琴[這裏](http://jsfiddle.net/Chanchalstack/PZCpf/4/) – Adidev

+0

你究竟是瞄準什麼?這解決了你的範圍解決問題,並執行你的動畫循環,因爲它們是 –

+0

其實我有一組點,當連接形式像水平和垂直連接的管道。我的目標是通過點/ pipes移動圓圈。這個答案工作,我現在沒有在我的控制檯上的錯誤,但if條件也不能正常工作。我是新來的這個,這是... 我有最後更新的小提琴[這裏..](http://jsfiddle.net/Chanchalstack/PZCpf/11/) 謝謝.. – Adidev

0

中的jsfiddle的代碼是從你貼什麼不同。

在的jsfiddle,您有:

if (pipeBegin.x == pipeEnds.x && pipeBegin.y >= pipeEnds.y) { 
     // endpoint y greater than start point y moving upwards 
     function animloop() { 
      if (ny > pipeEnds.y) { 
       console.log(nx + " : nx, ny : " + ny) 
       ctx.clearRect(0, 0, w, h); 
       drawCircle(nx, ny); 
       ny--; 
       nx = nx; 
      } else if (ny == pipeEnds.y) { 
       console.log(this) 
       cancelAnimationFrame(animloop); 
       this.callBegin(); 
      } 
      requestAnimFrame(animloop); 
     } 
     animloop(); 

    } 

您使用this.callBegin()功能animloop內,然後將this指的是全局對象window

您可以將animloop();更改爲animloop.call(this);animloop.apply(this);以約束正確的this

+0

爲了讀者的方便,我從小提琴中剪下了代碼。但它以其他方式工作。 是的,現在它指的是全局對象窗口,但建議的更改也無效。更新的小提琴[here](http://jsfiddle.net/Chanchalstack/PZCpf/1/) 謝謝 – Adidev