Home > Web Front-end > JS Tutorial > body text

## Where Do Callback Function Parameters Come From in JavaScript?

Susan Sarandon
Release: 2024-10-25 16:17:02
Original
123 people have browsed it

## Where Do Callback Function Parameters Come From in JavaScript?

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', {});
});
Copy after login

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
}
Copy after login

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
}
Copy after login

In the example provided, Node.js is responsible for passing request and response to the callback function whenever .get is invoked.

The above is the detailed content of ## Where Do Callback Function Parameters Come From in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!