2015-09-04 96 views
0

像往常一樣,我會在前面說這個問題,指出我非常處於學習階段。我試圖教自己的JavaScript,我正在讀一本書。當我完成時,我可能會繼續閱讀另一篇,但現在我需要幫助理解某些內容。在這個問題......需要幫助打破JavaScript功能

我會包括[回調]功能多數民衆贊成絆倒我開始:

function doMath(number1, number2, callback) { 
    var result = callback(number1, number2); 
    document.getElementById("theResult").innerHTML += ("The result is: " + result + "<br>"); 
} 

document.addEventListener(’DOMContentLoaded’, function() { 
    doMath(5, 2, function(number1, number2) { 
     var calculation = number1 * number2; 
     return calculation; 
    }); 
}, false); 

對於我的問題,我會盡量讓儘可能多的意義,因爲這裏可能,我只是不明白參數是如何傳遞給函數的。

例如,當我們調用doMath時,它看起來像包含參數5,2和函數。該功能似乎有兩個參數number1number2。我可以看到這兩個參數的值將在計算中使用,但我沒有看到他們如何到達那裏。我認爲52會傳遞給上面的doMath函數,而不是在那個參數函數中使用。

這些數字然後返回到doMath函數,並再次在這些參數中使用數字。

很明顯,它雖然,對不對?我遇到的問題是,我正在閱讀的這本書並沒有很好地解釋這一點。像其他許多事情一樣,它掩蓋了我認爲有必要真正理解的一些細節。最重要的是,當他包含HTML以提供完整示例時,我發現了一些錯誤實例。我只能看到這個,因爲我知道HTML。從一個全新的角度來看,如果我不完全理解一個函數是如何工作的,我該如何正確編寫一個函數呢?如果我不明白它在哪裏以及爲什麼,我怎麼能期望數據正常流動。

如果答案是'是',那些參數傳遞給回調函數,那就夠了。如果有人願意打算進一步打破這一流動,我會很感激。

回答

2

這裏的邏輯流程的快速擊穿編號:

function doMath(number1, number2, callback) { 
    // 4. doMath() is called from point 3. 
    // number1 = 5 
    // number2 = 2 
    // callback = the function containing 'var calculation = ...' 

    // 5. the callback function is executed. 
    var result = callback(number1, number2); 

    // 7. The result of the callback function (10) is set to the innerHTML 
    // of the below element. 
    document.getElementById("theResult").innerHTML += ("The result is: " + result + "<br>"); 
} 

// 1. The DOMContentLoaded event handler is defined 
document.addEventListener(’DOMContentLoaded’, function() { 
    // 2. The DOMContentLoaded event has fired, so this function handler is executed. 

    // 3. doMath is called, with the number 5 & 2, and the below function handler. 
    doMath(5, 2, function(number1, number2) { 
     // 6. The function is executed in doMath() from point 5 
     // number1 = 5 (as per the variable in doMath()) 
     // number2 = 2 (as per the variable in doMath()) 
     // note that the variables in this function are entirely separate from those in doMath(). 
     // Despite having the same name, they are in entirely different scopes. 

     var calculation = number1 * number2; 
     return calculation; // the value of 10 is returned to the call in doMath() 
    }); 
}, false); 
0

我認爲這是比較容易看到發生了什麼,如果你打破了回調到它自己的功能。

// doMath has two arguments, 5 and 2 
// The result is what is returned from our function 
// which used to be `callback` and is now `calculate` 
function doMath(number1, number2) { 
    var result = calculate(number1, number2); 
    ... 
} 

// This was `callback`. All it does is return the result 
// of multiplying 5 and 2 
function calculate(number1, number2) { 
    var calculation = number1 * number2; 
    return calculation; 
} 

// call doMath with 5 and 2 
doMath(5, 2); 

就是這樣。在你的例子中,calculate只是作爲參數傳入doMath