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

## Where Do Input Variables in JavaScript Callback Functions Come From?

Patricia Arquette
Release: 2024-10-26 18:21:29
Original
294 people have browsed it

## Where Do Input Variables in JavaScript Callback Functions Come From?

Javascript Callback Functions: Unraveling the Origin of Input Variables

When dealing with callback functions in JavaScript, a common question arises: where do the variables within the callback function originate? Let's delve into the answer, using a Node.js example for clarity.

In an example like:

<code class="javascript">router.get('/', function(req, res){
    res.render('index', {});
});</code>
Copy after login

The callback function takes two parameters, req and res. Understanding their origin is crucial.

Just like any other function invocation, the parameters of a callback function are provided when it's called. In this case, req and res are passed to the callback function by the router.get method.

Imagine the simplified version of router.get as:

<code class="javascript">router.get = function(endpoint, cb){
    // Logic to perform
    var request = {};
    var response = {};
    cb(request, response); // Invocation time
}</code>
Copy after login

When router.get is invoked with an endpoint and a callback, it creates request and response objects and passes them as parameters to the callback function. This effectively populates the req and res variables within the callback.

So, while the callback function is not immediately executed when passed as a parameter to another function, its parameters are established at the time of invocation. Just like in any other function, the parameters originate from the function call itself.

The above is the detailed content of ## Where Do Input Variables in JavaScript Callback Functions Come From?. 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!