我有以下简单示例来演示回调函数:
<script>
// The callback method
function meaningOfLife() {
console.log("The meaning of life is: 42");
}
// A method which accepts a callback method as an argument
function printANumber(number, meaningOfLife) {
console.log("The number you provided is: " + number);
}
// Driver method
printANumber(6, meaningOfLife);
</script>
预期结果
The number you provided is 6
The meaning of life is: 42
真实结果
The number you provided is 6
为什么我在为回调函数运行此示例时没有获得第二行?
答案 0 :(得分:4)
printANumber
方法接受回调作为参数,但从不调用它(或对其进行任何其他操作)。
只是将值传递给函数除了用该值填充参数外什么都不做。
如果您想使用该值,请使用它。
meaningOfLife();
如果您不重用变量名,这将更清楚。您有两个名为meaningOfLife
的变量。让我们改变一下:
function printANumber(number, callback) {
console.log("The number you provided is: " + number);
callback();
}
答案 1 :(得分:1)
如果你的printANumber
函数将接受回调函数作为参数,那么你需要实际调用/调用/执行回调。回调不会自动执行,因为它作为参数传递给printANumber
函数。将某些东西作为参数传递会填充函数中的参数变量,但它本身并不会对其执行任何操作。
要执行回调,您可以执行以下操作:
// The callback method
function meaningOfLife() {
console.log("The meaning of life is: 42");
}
// A method which accepts a callback method as an argument
function printANumber(number, callback) {
console.log("The number you provided is: " + number);
//Verify that what was passed as 'callback' is actually a function
if (typeof callback === 'function'){
callback(); //Actually execute the callback function
}
}
// Driver method
printANumber(6, meaningOfLife);
&#13;