简体   繁体   中英

Functions & callback functions in javaScript

Hello…I couldn't understand how those lines of javascript runs, any explanations?

// function declaration that takes in two arguments: a function for displaying
// a message, along with a name of a movie
function movies(messageFunction, name) {
  messageFunction(name);
}

// call the movies function, pass in the function and name of movie
movies(function displayFavorite(movieName) {
  console.log("My favorite movie is " + movieName);
}, "Finding Nemo");

Here you are calling the movies method passing a function (displayFavorite) and a string ("Finding Nemo").

movies(function displayFavorite(movieName) {
   console.log("My favorite movie is " + movieName);
}, "Finding Nemo");

And here the movies function execute the function passed with the paramter name.

function movies(messageFunction, name) {
   messageFunction(name);
}

So, when you pass the displayFavorite function it execute with the movieName("Finding Nemo"). hence, the console will log "My favorite movie is Finding Nemo"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM