简体   繁体   中英

pset8; cs50; javascript; when to use a named function and when to use an anonymous function in callback

In pset8, I have thought out 2 solutions for showing the information window when the user clicks on the marker.

 google.maps.event.addListener(marker, 'click', function() {
            showInfo(marker, articlesContent);
};

and

google.maps.event.addListener(marker, 'click', showInfo(marker, articlesContent));

why does the former/latter work or not work? I mean isn't showInfo also a function? Then why do you need to come up with another anonymous function to call the other function?

Apologies if this a newbie kind of mistake but I am completely new to Javascript and have been struggling for days for this pset. Would appreciate if someone could help me out!

In the first case, you are passing the function as a parameter. In the second case, you are calling the function.

Example of the first case: https://jsfiddle.net/anqpby6s/

document.getElementById("myBtn").addEventListener("click", function(){
    alert("Hello World!");
});

Notice the alert is called only when you click the button.

Example of the second case: https://jsfiddle.net/bwsps4b8/

document.getElementById("myBtn").addEventListener("click", alert("Hello World!"));

Notice the alert is called immediately when the code is run - that is not what you want.

You can research about Javascript Callbacks to go further into it, I found this in-depth article in a quick search: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

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