Home > Article > Web Front-end > Here are a few title options, keeping in mind the question format and the article\'s focus: **Direct and Concise:** * **Where do Variables in JavaScript Callback Functions Come From?** * **How are
The Origin of Parameters in JavaScript Callback Functions
In JavaScript, callback functions are executed after being passed as parameters to other functions. Understanding the origin of the variables used within callback functions can be a source of confusion.
In the Node.js example:
router.get('/', function(req, res){ res.render('index', {}); });
Variables req and res seem to materialize out of nowhere. However, they originate in the same manner as variables in any function invocation.
Take this non-callback function for example:
function add (a, b) { return a + b }
We understand that variables a and b come from the function invocation:
add(1,2)
The same principle applies to callback functions. When the function passed to router.get is invoked, it receives req and res as parameters.
Internally, the definition of router.get may look like this:
router.get = function(endpoint, cb){ //do something var request = {} var response = {} cb(request, response) // invocation time }
In your example, Node passes request and response as parameters to your callback function when get is invoked.
The above is the detailed content of Here are a few title options, keeping in mind the question format and the article\'s focus: **Direct and Concise:** * **Where do Variables in JavaScript Callback Functions Come From?** * **How are. For more information, please follow other related articles on the PHP Chinese website!