在您最初的 adds 函数中
function adds(num, foo) {
// this occurs on the initial function call, inside the scope of the adds function and does not carry over into the returned function.
foo();
// returning your function for later use, this will print 'hello' plus your passed in param.
return function(param) {
document.write("Hello ", param, "<br>");
};
}
// set your initial var
var x = 20;
// execute
adds(x/*20*/, function() {\
// does not relate to the num param inside the adds function for the return
x/*20*/ += 2;
})("World");
您的执行顺序已取消,为了清楚起见,我已将其分解了一些
const adds = (number, callback) => {
return param => {
// using callback within scope of returned function
let x = callback(number);
document.write(`Hello ${x} ${param}`);
}
};
let x = 20;
let callbackFunc = amount => (amount + 2);
let results = adds(x, callbackFunc);
对于一个更实用的真实世界返回函数,我经常在需要进行一些设置以使回调准备就绪的地方使用它们。这允许您在设置期间注入您的依赖项,而不必在所有地方都包含它们。 (有助于解耦测试和组织)
module.exports = function(db,logger) {
return async (req, res) => {
let result = await db.findOne(/* stuff */);
if (result.length === 0) {
logger.error('stuff not found');
res.sendStatus(404);
}
// do some processing, or not.
res.send(result);
};
};