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

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

Patricia Arquette
Release: 2024-10-26 08:52:02
Original
371 people have browsed it

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

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

We understand that variables a and b come from the function invocation:

add(1,2)
Copy after login

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

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!

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!