Callback Function Parameter Origin in JavaScript
Callback functions in JavaScript, as you mentioned, are executed after being passed as parameters to other functions. However, the origin of the parameters within the callback function can be confusing.
In the provided Node.js example:
router.get('/', function(req, res){ res.render('index', {}); });
The variables req and res are populated at the time the callback function is invoked. This concept is analogous to how parameters are passed in non-callback functions.
Consider this non-callback function:
function add (a, b) { return a b }
In this example, we understand that a and b come from the function's invocation, such as add(1,2).
Similarly, callback functions receive their parameters when they are invoked. In the case of router.get, it passes request and response objects to the callback function at invocation time.
To illustrate, consider a hypothetical definition of router.get:
router.get = function(endpoint, cb){ //do something var request = {} var response = {} cb(request, response) // invocation time }
In the example provided, Node.js is responsible for passing request and response to the callback function whenever .get is invoked.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3