Show me the code var chef = { name: 'Cuca', title: 'Mestre' }; whoIsTheChef(); changeChef(); whoIsTheChef(); function whoIsTheChef() { console.log(chef.title + ' ' + chef.name); } /* Random function from third-party script */ function changeChef() { chef = { name: 'Benta', title: 'Dona' }; }
Show me the code > Mestre Cuca > Dona Benta var chef = { name: 'Cuca', title: 'Mestre' }; whoIsTheChef(); changeChef(); whoIsTheChef(); function whoIsTheChef() { console.log(chef.title + ' ' + chef.name); } /* Random function from third-party script */ function changeChef() { chef = { name: 'Benta', title: 'Dona' }; }
Show me the code /* Single global object solution */ var KitchenApp = KitchenApp || {}; KitchenApp.chef = { name: 'Cuca', title: 'Mestre' }; whoIsTheChef(); changeChef(); whoIsTheChef(); function whoIsTheChef() { console.log(KitchenApp.chef.title + ' ' + KitchenApp.chef.name); } /* Random function from third-party script */ function changeChef() { chef = { name: 'Benta', title: 'Dona' }; }
Source: http://www.freeimages.com/photo/kitchen-tools-1237100 Module Pattern Single Responsibility Principle Privacy (clean global scope) with IIFEs Independency & Reusability Locked state
Module 1. a separable component, frequently one that is interchangeable with others, for assembly into units of differing size, complexity, or function. Source: http://dictionary.reference.com/browse/module?s=t
Show me the code var ingredientsForPasta = ['Pasta', 'Water', 'Salt']; // IIFE - Immediately Invoked Function Expression var KitchenApp = (function() { 'use strict'; // Isolated scope with access to Global console.log(ingredientsForPasta); var ingredientsForSauce = ['Tomato', 'Olive Oil', 'Basil']; console.log(ingredientsForSauce); }()); console.log(ingredientsForPasta); // Error: ingredientsForSauce is not defined // No access to variables defined inside de IIFE console.log(ingredientsForSauce);
Show me the code var ingredientsForPasta = ['Pasta', 'Water', 'Salt']; // IIFE - Immediately Invoked Function Expression var KitchenApp = (function() { 'use strict'; // Isolated scope with access to Global console.log(ingredientsForPasta); var ingredientsForSauce = ['Tomato', 'Olive Oil', 'Basil']; console.log(ingredientsForSauce); }()); console.log(ingredientsForPasta); // Error: ingredientsForSauce is not defined // No access to variables defined inside de IIFE console.log(ingredientsForSauce); > [ 'Pasta', 'Water', 'Salt' ] > [ 'Tomato', 'Olive Oil', 'Basil' ] > [ 'Pasta', 'Water', 'Salt' ] > ಠ_ಠ
Show me the code (function(){ var spaghetti = document.body.dataset.spaghetti; if (spaghetti !== undefined) { require('Recipe.' + spaghetti).cook(); } else { document.write('Y u no select a recipe?'); } }());
Show me the code (function(){ var spaghetti = document.body.dataset.spaghetti; if (spaghetti !== undefined) { require('Recipe.' + spaghetti).cook(); } else { document.write('Y u no select a recipe?'); } }()); kitchenApp.js index.html