Forum Moderators: open
(function($) {
// do stuff
})($); ... the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $
(function($) {
// do stuff
})(jQuery);
(function($) {
// do stuff
})($);
<!DOCTYPE html>
<body>
<button id="originalCounter">Original Counter</button>
<button id="contaimatingCounter">Contaminate</button>
<button id="safeCounter">Safe Counter</button>
<script>
var counter = 0; // this is going to live at the global scope
function incrementCounter() {
counter = counter + 1;
console.log(`originalCounter: ${counter}`);
}
document.querySelector('#originalCounter').addEventListener('click', incrementCounter);
</script>
<script>
var counter = 1; // this overwrites the value at the global scope
function contaminateCounter() {
counter = counter + 1;
console.log(`contaimatingCounter: ${counter}`);
}
document.querySelector('#contaimatingCounter').addEventListener('click', contaminateCounter);
</script>
<script>
(function () {
var counter = 0; // this is function scoped, not accessible outside of the IIFE
function incrementSafely() {
counter = counter + 1;
console.log(`safeCounter: ${counter}`);
}
document.querySelector('#safeCounter').addEventListener('click', incrementSafely);
})(); // immediately invoke this anonymous function, preventing contamination of the global scope
</script>
</body>
;(function($) {