JavaScript Patterns to Clean Up Your Code Dan Wahlin.

Slides:



Advertisements
Similar presentations
JavaScript: A Language of Many Contrasts
Advertisements

Closure Douglas Crockford. Block Scope { let a; { let b; … a … … b … } … a … }
Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 Chapter 12 More OOP, Interfaces, and Inner Classes.
Tutorial 6 & 7 Symbol Table
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
T HE B ASICS O F S OFTWARE A RCHITECTURE F OR.NET D EVELOPERS Dan Douglas | Senior Software Developer/ Architect Blog:
+ Informatics 122 Software Design II Lecture 8 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
CSE 190M Extra Session #5 JavaScript scope and closures slides created by Marty Stepp
Lesson15. JavaScript Objects Objects encapsulate data (properties) and behavior(methods); the properties and the methods of an object are tied together.
Chapter 6: Functions.
IT PUTS THE ++ IN C++ Object Oriented Programming.
Taking JavaScript Seriously IS NOT THE WORST IDEA.
IS JAVASCRIPT OBJECT-ORIENTED? Contains objects Data Methods Doesn’t have classes Does have constructors Does have prototype functions Doesn’t provide.
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
Design Patterns.
CIT241 Prerequisite Knowledge ◦ Variables ◦ Operators ◦ C++ Syntax ◦ Program Structure ◦ Classes  Basic Structure of a class  Concept of Data Hiding.
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Tutorial 2 Variables and Objects. Working with Variables and Objects Variables (or identifiers) –Values stored in computer memory locations –Value can.
Aspect Oriented Programming Scott Nykl CSSE 411 Senior Seminar.
SAMANVITHA RAMAYANAM 18 TH FEBRUARY 2010 CPE 691 LAYERED APPLICATION.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
JavaScript, Fourth Edition
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
Object Oriented JavaScript. JavaScript Really only 4 types in JavaScript – number, string, boolean – Object (includes arrays) Remember that an object.
Improving the Quality of Existing Code Svetlin Nakov Telerik Corporation
Computers and Scientific Thinking David Reed, Creighton University Functions and Libraries 1.
1 Scope Scope describes the region where an identifier is known, and semantic rules for this.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Design Patterns Façade, Singleton, and Factory Methods Team Good Vibrations (1)
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Refactoring. Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative.
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
Programming Perl in UNIX Course Number : CIT 370 Week 6 Prof. Daniel Chen.
Julian on JavaScript: Functions Julian M Bucknall, CTO.
IOS Best Practices: Avoid the Bloat
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
Introduction to Computing Using Python Namespaces – Local and Global  The Purpose of Functions  Global versus Local Namespaces  The Program Stack 
JavaScript scope and closures
04 |Sharing Code Between Windows 8 and Windows Phone 8 in Visual Studio Ben Riga
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
1 COS 260 DAY 12 Tony Gauvin. 2 Agenda Questions? 5 th Mini quiz –Chapter 5 40 min Assignment 3 Due Assignment 4 will be posted later (next week) –If.
MTA EXAM HTML5 Application Development Fundamentals.
JavaScript for C# developers Dhananjay Microsoft MVP
Department of Electronic & Electrical Engineering Functions Parameters Arguments Pointers/dereference & * Scope Global/Local Storage Static/Automatic.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Object Oriented JavaScript. JavaScript Really only 4 types in JavaScript – number, string, boolean – Object (includes arrays) Remember that an object.
Javascript Design Patterns. AMD & commonJS. RequireJS Marc Torrent Vernetta.
Introduction to Classes and Objects CS-2303, C-Term C++ Program Structure Typical C++ Programs consist of:– main –A function main –One or more classes.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
MIS Professor Sandvig MIS 324 Professor Sandvig
Names and Attributes Names are a key programming language feature
SPC Developer 6/10/2018 © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Section 13 – Using External JavaScript Modules
Dr. Charles W. Kann III JavaScript Objects Dr. Charles W. Kann III
Functional Programming with Java
Modern JavaScript Develop And Design
Programming Logic and Design Fourth Edition, Comprehensive
Namespaces – Local and Global
CS 350 – Software Design Singleton – Chapter 21
CSE 341 Lecture 27 JavaScript scope and closures
Developing and testing enterprise Java applications
Object-Oriented PHP (1)
Namespaces – Local and Global
Presentation transcript:

JavaScript Patterns to Clean Up Your Code Dan Wahlin

Blog

Agenda Function Spaghetti Code Closures to the Rescue Object Literals and Namespaces Prototype Pattern Revealing Module Pattern Revealing Prototype Pattern

Function Spaghetti Code

Problems with Function Spaghetti Code Mixing of concerns No clear separation of functionality or purpose Variables/functions added into global scope Potential for duplicate function names Not modular Not easy to maintain No sense of a “container”

Agenda Function Spaghetti Code Closures to the Rescue Object Literals and Namespaces Prototype Pattern Revealing Module Pattern Revealing Prototype Pattern

Ravioli Code

Advantages of Ravioli Code Objects encapsulate and decouple code Loosely coupled Separation of Concerns –Variables/functions are scoped –Functionality in closures Easier to maintain

What is a Closure? “…an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.” ~ Douglas Crockford

Non-Closure Example function myNonClosure() { var date = new Date(); return date.getMilliseconds(); } Variable lost after function returns

Closure Example function myClosure() { var date = new Date(); //nested function return function () { return date.getMilliseconds(); }; } Variable stays around even after function returns

Agenda Function Spaghetti Code Closures to the Rescue Object Literals and Namespaces Prototype Pattern Revealing Module Pattern Revealing Prototype Pattern

Encapsulating Data with Object Literals Quick and easy All members are available Well suited for data var calc = { tempValue: 1, add: function(x, y) { return x + y; } };

Namespaces Encapsulate your code in a namespace: var my = my || {};

Using Namespaces my.calc = { tempValue: 1, add: function(x, y) { return x + y; } };

Agenda Function Spaghetti Code Closures to the Rescue Object Literals and Namespaces Prototype Pattern Revealing Module Pattern Revealing Prototype Pattern

The Prototype Pattern Benefits: –Leverage JavaScript’s built-in features –“Modularize” code into re-useable objects –Variables/functions taken out of global namespace –Functions loaded into memory once –Possible to “override” functions through prototyping Challenges: –“this” can be tricky –Constructor separate from prototype definition

Prototype Pattern Structure var Calculator = function(eq) { this.eqCtl = document.getElementById(eq); }; Calculator.prototype = { add: function (x, y) { var val = x + y; this.eqCtl.innerHTML = val; } }; var calc = new Calculator('eqCtl'); calc.add(2,2);

Agenda Function Spaghetti Code Closures to the Rescue Object Literals and Namespaces Prototype Pattern Revealing Module Pattern Revealing Prototype Pattern

The Revealing Module Pattern Benefits: –“Modularize” code into re-useable objects –Variables/functions taken out of global namespace –Expose only public members Challenges: –Functions may be duplicated across objects in memory when not using singleton –Not easy to extend –Some complain about debugging

Revealing Module Structure var calculator = function(eq) { var eqCtl = document.getElementById(eq), doAdd = function(x,y) { var val = x + y; eqCtl.innerHTML = val; }; return { add: doAdd }; //Expose public member }('eqCtl'); calculator.add(2,2);

Agenda Function Spaghetti Code Closures to the Rescue Object Literals and Namespaces Prototype Pattern Revealing Module Pattern Revealing Prototype Pattern

The Revealing Prototype Pattern Benefits: –Combines Prototype and Revealing Module patterns –“Modularize” code into re-useable objects –Variables/functions taken out of global namespace –Expose only public members –Functions loaded into memory once –Extensible Challenges: –"this" keyword can be tricky –Constructor separate from prototype definition

Revealing Prototype Structure var Calculator = function (eq) { this.eqCtl = document.getElementById(eq); }; Calculator.prototype = function() { var doAdd = function (x, y) { var val = x + y; this.eqCtl.innerHTML = val; }; return { add : doAdd }; }(); var calc = new Calculator('eqCtl'); calc.add(2,2);

Summary Function spaghetti code is bad, Ravioli code is good Closures provide encapsulation Key patterns: –Prototype Pattern –Revealing Module Pattern –Revealing Prototype Pattern Which pattern should you use? You decide….

Thank weblogs.asp.net/dwahlin

Download the sample code: