试图理解回调函数

Trying to understand Callback function

我正在创建一个简单的回调函数,试图了解它的工作原理。

function cbFunction(x, y, z) {
  return x + y + z
}

function caller(x, y, z, cbFunction) {
  console.log('In caller function!')
  // your code here
  if (typeof cbFunction === "function") {
    cbFunction (x, y, z)
  }
}

caller(1, 2, 3, cbFunction)

我正在调用函数内部调用 cbFunction。你能帮我理解为什么它不添加 x、y、z 吗?我是初学者,正在学习 JS,感谢您的帮助!

它正在添加数字 - 您只是没有对 cbFunction 编辑的结果做任何事情。

相反,return return 由 cbFunction 编辑的结果:

function cbFunction(x, y, z) {
  return x + y + z
}

function caller(x, y, z, cbFunction) {
  console.log('In caller function!')
  // your code here
  if (typeof cbFunction === "function") {
    return cbFunction(x, y, z); //<-- return
  }
}

console.log(caller(1, 2, 3, cbFunction))