Skip to content

Instantly share code, notes, and snippets.

@henrahmagix
Created February 4, 2013 10:28
Show Gist options
  • Save henrahmagix/4706048 to your computer and use it in GitHub Desktop.
Save henrahmagix/4706048 to your computer and use it in GitHub Desktop.
An explanation of the advantages of anonymous functions in Javscript, and the pitfalls one faces when not using them.

Javascript Anonymous Functions

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.

Global Functions

Here we use the onload method of document.body.

index.html

<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>

index.js

function changeColor(color) {
    document.body.setAttribute('class', 'red');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment