2014-12-03 37 views
2

當我將Math.PI的比較右側替換爲我的時候,我有兩個'if less then'塊似乎不適合我變量,this.bottomChainAngleRads。當我使用一個變量進行比較時,Javascript比這個失敗了

語境:我動畫鏈兩個齒輪之間,所以迭代的兩個齒輪隱藏/顯示它的鏈接,他們旋轉

代碼早些時候,該變量初始化所用牙齒數學,而不是一個字符串。

this.bottomChainAngleRads = Math.PI + 2 * Math.atan2(...); 

然後我想用它做的東西每過一段時間:

this.step = function() { 
    console.log('this.bottomChainAngleRads = ' + this.bottomChainAngleRads // Just over PI. Usually about 3.4. 
       + ' ' + $.isNumeric(this.bottomChainAngleRads));   // Always true. 

    // Counting the passing through each if block. Expecting a little in each. 
    var frontDisplay = 0, frontHide = 0, rearDisplay = 0, rearHide = 0; 

    $(this.frontGear.div).find('.geartooth').each(function(index, el) { 
    var totalRadians = measureRotation(el); 
    console.log('front totalRadians = ' + totalRadians + ' ' // From 0 to TWO_PI 
       + (totalRadians < this.bottomChainAngleRads)); // Always false. WTF. 
    if (totalRadians < this.bottomChainAngleRads) { // <================ FAILS. NEVER TRUE. 
    // if (totalRadians < Math.PI) { // MOSTLY CORRECT, but expectedly off by minor angle. 
     ++frontDisplay; 
     // .. do stuff 
    } else { 
     ++frontHide; 
     // .. do other stuff 
    } 
    }); 

    $(this.rearGear.div).find('.geartooth').each(function(index, el) { 
    var totalRadians = measureRotation(el); 
    console.log('rear totalRadians = ' + totalRadians + ' '  // From 0 to TWO_PI 
       + (totalRadians < this.bottomChainAngleRads)); // Always false. WTF. 
    if (totalRadians < this.bottomChainAngleRads) { // <================ FAILS. NEVER TRUE. 
    // if (totalRadians < Math.PI) { // MOSTLY CORRECT, but expectedly off by minor angle. 
     ++rearHide; 
     // .. do stuff 
    } else { 
     ++rearDisplay; 
     // .. do other stuff 
    } 
    }); 

    // Below I expected approximately a 50/50 split on each gear. Instead, I get... 
    console.log('front: ' + frontDisplay + ', ' + frontHide  // Nothing, All. 
       + '; rear: ' + rearDisplay + ', ' + rearHide); // All, Nothing 
} 

對不起,冗長的代碼,而是因爲我覺得我已經嘗試了這麼多東西,我想給更大的圖片。

+0

這是一個範圍問題。 '.each'裏面的'this'是指DOM元素而不是你的對象。在'.each'之外使用'var that = this',然後使用'that'適當的 – devnull69 2014-12-03 12:49:04

回答

0

each回調的內部的環境是不是你的對象實例了,this點個人DOM元素(.geartooth),這顯然不具有財產bottomChainAngleRads

最簡單的解決方法是保存正確的上下文引用。試試這個:

var self = this; 
$(this.rearGear.div).find('.geartooth').each(function(index, el) { 
    var totalRadians = measureRotation(el); 
    if (totalRadians < self.bottomChainAngleRads) { 
    ... 
}); 
+0

謝謝。我現在可以停止我的頭撞。 – Anm 2014-12-03 12:55:54

+0

您還可以使用jQuery的[proxy()](http://api.jquery.com/jQuery.proxy/)來設置上下文'.each($。proxy(myFunction,this))'。這對事件處理程序特別有用,它可以方便地使用代理也處理的部分應用程序。 – Sukima 2014-12-03 12:58:18

+0

例如:http://jsbin.com/hivila/1/edit?html,js,output – Sukima 2014-12-03 13:11:23