On Github cabaret / JSPRES
var x = 5; function globalVar() { x = 3; console.log(x); // 3 } console.log(x); // 3
x is a global variable. inside the function, we access x and overwrite it this might give us unexpected results. bad.
function impliedGlobal() { x = 2; } function localVar() { var y = 2; } console.log(x); // 2 console.log(y); // y is undefined
the difference between using and not using var. not using var creates an implied global variable. can be dangerous for reasons stated before (overwriting) using the var statement makes the variable (y) local to the function scope.
var x = 5; function localVar() { var x = 2; console.log(x); // 2 } console.log(x); // 5
local variable is local. global variable is global. they dont interfere.
console.log(globalVar); // function globalVar() { ... } console.log(localVar); // function localVar() { ... }
function randomFunction() { var a = b = 0; } console.log(a); // undefined console.log(b); // 0
right to left evaluation b = 0; b doesnt exist so it is declared as an implied global. a is local to the function
crockford. name collisions. will explain later. kthx.
Moving from global namespace pollution towards a modular style.
function initSlider() { /* ... */ } function initModal() { /* ... */ } function initSearch() { /* ... */ } $(document).ready(function() { initSlider(); initModal(); initSearch(); });
each function creates a new global. anti pattern. how2fix? IIFE
Create a function and immediately execute it:
(function() { alert('Kunstmaan'); })();
can also be written as (function () {}()); something about performance.
(function ($) { var initSlider = function() { /* ... */ }; var initSearch = function() { /* ... */ }; var initModal = function() { /* ... */ }; $(document).ready(function() { initSlider(); initSearch(); initModal(); }); }(jQuery));
multiple var statements
Slight optimalisation by using one var statement
(function ($) { var init, initSlider, initModal, initSearch; init = function () { initSlider(); initModal(); initSearch(); }; initSlider = function() { /* ... */ }; initSearch = function() { /* ... */ }; initModal = function() { /* ... */ }; $(document).ready(function () { init(); }); })(jQuery);
one var statement
var myApp = (function ($) { var init, initSlider, initModal; init = function () { initSlider(); initModal(); }; initSlider = function() { /* ... */ }; initModal = function() { /* ... */ }; return { init: init }; }(jQuery)); $(document).ready(function () { myApp.init(); });
var myApp = (function ($) { var init, initSlider, initSearch, search; init = function () { initSlider(); initSearch(); }; initSlider = function() { /* ... */ }; initSearch = function() { /* ... */ }; search = function() { /* ... */ }; return { init: init, search: search }; }(jQuery)); $(document).ready(function () { myApp.init(); }); $('#btn').click(function () { myApp.search($('#someInput').val()); });
One Kunstmaan namespace with different plugins