Anonymous functions allow us to compartmentalise our code and avoid [polluting the global scope][global scope]. The difference between using and not using an anonymous function is explained with a basic example of changing the background color to red when the DOM is ready.
Here we use the onload
method of document.body
.
<html>
<head>
<title>Our example</title>
<style type="text/css">
.blue {
background-color: #00f;
}
.red {
background-color: #f00;
}
</style>
</head>
<body class="blue" onload="changeColor();">
<h1>This is our example</h1>
</body>
</html>
function changeColor(color) {
document.body.setAttribute('class', 'red');
}