20 November 2020, 1:56 pm by antelove19

Sources:
Oreilly Head First JavaScript Programming 1
How to use an anonymous function
So, we’re creating a function to handle the load event, but we know it’s a "one time" function because the load event only happens once per page load. We can also observe that the window.onload
property is being assigned a function reference—namely, the function reference in handler. But because handler is a one time function, that name is a bit of a waste, because all we do is assign the reference in it to the window.onload
property.
Anonymous functions give us a way to clean up this code. An anonymous function is just a function expression without a name that’s used where we’d normally use a function reference. But to make the connection, it helps to see how we use a function expression in code in an anonymous way:
First remove the handler variable so this becomes a function expression.
function handler() {
alert("Yeah, that page loaded!");
}
window.onload = handler;
Then assign the function expression directly to the window.onload
property.
window.onload = function() {
alert("Yeah, that page loaded!");
};
-
Oreilly, "Oreilly Head First JavaScript Programming", page 477 ↩