Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Javascript coding-and-design-patterns


Published on

Talk given at MercadoLibre, as a first idea, about how to organise your JavaScript code.

Published in: Technology
  • Be the first to comment

Javascript coding-and-design-patterns

  1. 1. JavaScript Coding & Design Patterns
  2. 2. Content Getting Started JavaScript Style Guide Namespace Dependencies’s Declaration Dealing With Browsers Separation of Concerns Init-time Branching DOM Scripting Events Design Patterns Singleton Module Pattern Prototypal Inheritance The new keyword The Object.create method
  3. 3. Getting Started JavaScript Style Guide, Namespace & Dependencies’s Declaration
  4. 4. JavaScript Style Guide
  5. 5. Namespace JavaScript doesn’t have built-in namespaces Reduce globals variables Avoid naming collisions Avoid name prefixing
  6. 6. Namespace var fleet = fleet || {};
  7. 7. Dependencies’s Declaration Explicit declaration the modules at the top Easy to find and resolve dependencies Working with local is faster than working with global Smaller code when minifies the module for production
  8. 8. Dependencies’s Declaration function Car() { var Motor = vehicle.Motor, Wheel = vehicle.Wheel; }
  9. 9. Dealing with Browsers Separation of Concerns, Init-time Branching, 
 DOM Scripting & Events
  10. 10. Separation of Concerns Improves the delivery to a vast array of user agents Enhance the site progressively Test it without CSS Test it without JS
  11. 11. Init-time Branching Optimization pattern to test a condition only once Common used on browser feature detection
  12. 12. Init-time Branching var w = window, modern = w.addEventListener !== undefined, on = modern ? ‘addEventListener’ : ‘attachEvent’, click = modern ? ‘click’ : ‘onclick’; ! document.body[on](click, function(){});
  13. 13. DOM Scripting Inconsistently implemented across browsers Avoiding DOM access in loops Assigning DOM reference to local variables Use selector APIs methods Caching the length when iteration over a HTML collection Change the DOM outside the live document
  14. 14. DOM Scripting var collection = document.querySelectorAll('.cars'), collectionLength = collection.length, item = 0; function addWheel(){ for (item; item < collectionLength; item ++) { var car = collection[item]; car.setAttribute('data-item-number', item); car.setAttribute('data-item-message', message[item]); } }
  15. 15. Events Attaching listeners unobtrusively helps reutilisation Delegates event helps performance
  16. 16. Event Delegation var container = document.querySelector(‘.parking’), child; ! container.addEventListener(‘click’, function(ev){ if(‘data-car’)){ child =; child.setAttribute(‘selected’, ‘selected’); } });
  17. 17. Functions Scope, Hoisting, Configuration Object, IIFE
  18. 18. Functions They have a variety of tasks, other languages may have special syntax for it They are first-class objects They provide scope Can have their own properties and methods Can be passed as argument and returned by other functions Can be augmented, assigned to variables, referenced and deleted
  19. 19. Scope JavaScript has not special syntax to denote 
 private, protected or public properties or methods JavaScript is a function scope language
  20. 20. Scope var code = 93854782; ! function Car(){ var code; }
  21. 21. Hoisting JavaScript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function.
  22. 22. Hoisting function Car(){ var code, motor, wheels, doors; ! }
  23. 23. Configuration Object Car({ 'code': 'A195', 'wheels': 4, 'doors': 3, 'color': 'blue' });
  24. 24. Immediately-Invoked Function Expression It is a syntax that enables you to execute a function as soon as it is defined It provides a scope sandbox for your initialisation code It can receive arguments It can return values It can be used when define object properties It helps doing work wrapped without leaving any global variable
  25. 25. IIFE Immediately-Invoked Function Expression (function(){ /* code */ }());
  26. 26. Design Patterns Singleton, Module Pattern
  27. 27. Singleton Only one instance of a specific class A simple way is creating a object literal Every time you use the object literal syntax you are creating a singleton It is possible to use the new keyword to create a singleton
  28. 28. Singleton simple way var parking = {};
  29. 29. Singleton with the new keyword function Parking(){ if(typeof Parking.instance === 'object') { return Parking.instance; } Parking.instance = this; return this; }
  30. 30. Module Pattern It provides structure and helps organise your code as it grows It provides the tools to create self-container decoupled pieces of code It is a combination of the following patterns Namespaces Immediate functions Private and privileged members Declaring dependencies
  31. 31. Module Pattern var parking = (function () { var _places = [], // private module = {}; // public ! module.isTaken = function(placeNumber){}; ! return module; }());
  32. 32. Module Pattern (function(exports) { var _places = [], module = {}; // public ! module.isTaken = function(placeNumber){}; ! exports.module; }(parking));
  33. 33. Prototypal Inheritance The new keyword & The Object.create() method
  34. 34. Prototypal Inheritance JavaScript is classified as having a prototype-based object model. It is simple, a new object can inherit the properties of an old object. Every function has a prototype property and it contains an object. Add functionality by adding methods and properties to the prototype.
  35. 35. The new keyword function Car(brand, doors){ this.brand = brand; this.doors = doors; return this; } ! = function(){} ! var peugeot = new Car(‘peugeot’, 4);
  36. 36. The Object.create() method var Car = { ‘run’: function(){}, ‘init’: function(brand, doors){ this.brand = brand; this.doors = doors; } } ! var peugeot = Objetc.create(Car);