SlideShare ist ein Scribd-Unternehmen logo
1 von 15
JavaScript Patterns

      Part One
Patterns


 ● Design Patterns
    ○ Gang of Four
    ○ Templates for any language


 ● Coding Patterns
    ○ JavaScript-specific strategies
    ○ Our main focus in this series


 ● Antipatterns
    ○ Common despite being dangerous
    ○ Introduce more problems than they solve
Object-Oriented
 ● JavaScript IS an object-oriented language

 ● 5 primitive types - these are not objects:
     ○ number, string, boolean, null, undefined
     ○ three of the primitives have object wrappers
         ■ Number(), String(), Boolean()

 ● 3 global properties
     ○ Infinity, NaN, undefined

 ● 13 global methods
    ○ decodeURI, encodeURI, escape, unescape, isFinite, isNaN,
      parseFloat, parseInt, eval, String, Number, decodeURIComponent,
      encodeURIComponent
Object-Oriented


 ● Objects
    ○ collection of key:value pairs
        ■ associative array, dictionary, hash
    ○ mutability - objects can be modified
    ○ two types:
        ■ Native JavaScript - defined by ES standard
           ■ built-in
           ■ user-defined (var o = {};)
        ■ Host - defined by browser/host
           ■ browser
           ■ DOM
Object-Oriented


 ● Functions are objects - can have:
    ○ properties
    ○ methods (other functions)


 ● Ther are no classes!
    ○ GoF: "Prefer object composition over inheritance."


 ● Prototypes
    ○ provide an 'inheritance-like' capability
    ○ 'prototype' is an object, not a class
    ○ every function object has a prototype property
    ○ avoid adding to JS built-ins
    ○ utilize for custom constructors
ECMAScript 5


● Standard which JS is based on


● Version 5
   ○ new objects, methods and properties
   ○ 'strict mode'
       ■ removes features
       ■ makes programs simpler and less error prone
       ■ backward compatible
       ■ 'use strict' once per scope
   ○ not yet supported
   ○ keep an eye out for the transition
JSLint


● JavaScript
   ○ interpreted
   ○ no static compile-time checks = hard to debug


● Douglas Crockford
   ○ this tool "will hurt your feelings"
   ○ but also inspire confidence


● jslint.com
    ○ improve code quality
    ○ find syntax errors
    ○ find simple omissions
    ○ has a wide variety of settings: 'strict mode' compliance
The Console


● present in most browsers
   ○ Gecko: Firebug
   ○ Webkit: Web Inspector
   ○ Trident: Developer Tools


● less obtrusive than alert()


● console's output methods
   ○ console.log() outputs params
   ○ console.dir() enumerates
   ○ type in directly
Authoring Essentials


 ● Write Maintainable Code
    ○ readable
    ○ consistent
    ○ predictable
    ○ focused
    ○ documented


 ● Know Your Scope
    ○ local
    ○ global
Global


● declared outside of any function


● browsers provide access via 'window' property


● shared among all code, including any 3rd party libs


● use as few as possible, strategies include:
   ○ namespaces
   ○ immediate functions
   ○ 'var' declarations
Global
● 'var' declarations
    ○ var inside any function
        ■ "var foo = {}"
            ■ makes a foo object local to that function
        ■ "bar = {}"
            ■ adds a bar property to the global
        ■ "var nix = bix = 0"
            ■ makes a local nix and a global bix
    ○ var outside any function
        ■ makes a global variable (not a global property)


● 'var's CAN NOT be deleted, properties can


● ES5 strict mode throws error for undeclared variable assignments
Variable Hoisting


● all var declarations in a function act as if declared at top


● so just declare them at top to avoid confusion
                      var scope = "global";
                      function f(){
                          alert(scope);        //undefined
                          var scope = "local";
                          alert(scope);        //local
                      }
                      f();
                      ____________________________


                      var scope = "global";
                      function f(){
                          var scope;
                          alert(scope);       //undefined
                          scope = "local";
                          alert(scope);       //local
                      }
                      f();
Loops


● 'for' loop
    ○ cache the length value of your collection
         ■ Array
         ■ HTMLCollection
            ■ especially bad
            ■ live queries on the DOM
    ○ exception: when modifying length of collection


● try to avoid nested loops at all costs
    ○ look for other ways
    ○ ask around
    ○ might not be obvious, but worth it
Loops


● 'for in' loops
    ○ enumeration of objects
         ■ ...technically can be used with arrays
         ■ ...but not recommended
    ○ hasOwnProperty()
         ■ important defensive strategy
         ■ filters out prototype chain
         ■ ...but has performance implication
         ■ if your object has redefined hasOwnProperty()
              ■ Object.prototype.hasOwnProperty.call(obj, i)
Augmenting Built-ins


● it's done via 'prototype'
     ○ Object.prototype.newMethodForAll = function(){};


● but it's best not done at all
   ○ less predictable
   ○ other devs won't get it
   ○ it will show up in loops that don't defend against it


● exception conditions - all 3 must be met!
   1. if ES or JS will eventually implement anyway
   2. if you are sure it doesn't already exist
   3. you clearly document AND communicate to your team
   4. example: Array.isArray

Weitere ähnliche Inhalte

Was ist angesagt? (7)

Lesson 4
Lesson 4Lesson 4
Lesson 4
 
Python intro
Python introPython intro
Python intro
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
 
Storage classes
Storage classesStorage classes
Storage classes
 
Coding convention
Coding conventionCoding convention
Coding convention
 
How to write Ruby extensions with Crystal
How to write Ruby extensions with CrystalHow to write Ruby extensions with Crystal
How to write Ruby extensions with Crystal
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 

Andere mochten auch (19)

JavaScript: Patterns, Part 3
JavaScript: Patterns, Part  3JavaScript: Patterns, Part  3
JavaScript: Patterns, Part 3
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Android security
Android securityAndroid security
Android security
 
Code Kata
Code KataCode Kata
Code Kata
 
iOS release engineering
iOS release engineeringiOS release engineering
iOS release engineering
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Clean Code
Clean CodeClean Code
Clean Code
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
JavaScript: The Good Parts
JavaScript: The Good PartsJavaScript: The Good Parts
JavaScript: The Good Parts
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in Flex
 
Classic Mistakes
Classic MistakesClassic Mistakes
Classic Mistakes
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Function Points
Function PointsFunction Points
Function Points
 
OpenGL ES on Android
OpenGL ES on AndroidOpenGL ES on Android
OpenGL ES on Android
 
Software Development Fundamentals
Software Development FundamentalsSoftware Development Fundamentals
Software Development Fundamentals
 
iOS: A Broad Overview
iOS: A Broad OverviewiOS: A Broad Overview
iOS: A Broad Overview
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
iOS App Dev
iOS App Dev iOS App Dev
iOS App Dev
 

Ähnlich wie JavaScript: Patterns, Part 1

JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009
Mario Heiderich
 
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
Android Variants, Hacks, Tricks and Resources presented at AnDevConIIAndroid Variants, Hacks, Tricks and Resources presented at AnDevConII
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
Opersys inc.
 

Ähnlich wie JavaScript: Patterns, Part 1 (20)

Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Ruxmon feb 2013 what happened to rails
Ruxmon feb 2013   what happened to railsRuxmon feb 2013   what happened to rails
Ruxmon feb 2013 what happened to rails
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
 
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
 
24 uses for perl6
24 uses for perl624 uses for perl6
24 uses for perl6
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
Diagnosing HotSpot JVM Memory Leaks with JFR and JMCDiagnosing HotSpot JVM Memory Leaks with JFR and JMC
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part II
 
JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic Linker
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
Android Variants, Hacks, Tricks and Resources presented at AnDevConIIAndroid Variants, Hacks, Tricks and Resources presented at AnDevConII
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
 
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan KrausHTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

JavaScript: Patterns, Part 1

  • 2. Patterns ● Design Patterns ○ Gang of Four ○ Templates for any language ● Coding Patterns ○ JavaScript-specific strategies ○ Our main focus in this series ● Antipatterns ○ Common despite being dangerous ○ Introduce more problems than they solve
  • 3. Object-Oriented ● JavaScript IS an object-oriented language ● 5 primitive types - these are not objects: ○ number, string, boolean, null, undefined ○ three of the primitives have object wrappers ■ Number(), String(), Boolean() ● 3 global properties ○ Infinity, NaN, undefined ● 13 global methods ○ decodeURI, encodeURI, escape, unescape, isFinite, isNaN, parseFloat, parseInt, eval, String, Number, decodeURIComponent, encodeURIComponent
  • 4. Object-Oriented ● Objects ○ collection of key:value pairs ■ associative array, dictionary, hash ○ mutability - objects can be modified ○ two types: ■ Native JavaScript - defined by ES standard ■ built-in ■ user-defined (var o = {};) ■ Host - defined by browser/host ■ browser ■ DOM
  • 5. Object-Oriented ● Functions are objects - can have: ○ properties ○ methods (other functions) ● Ther are no classes! ○ GoF: "Prefer object composition over inheritance." ● Prototypes ○ provide an 'inheritance-like' capability ○ 'prototype' is an object, not a class ○ every function object has a prototype property ○ avoid adding to JS built-ins ○ utilize for custom constructors
  • 6. ECMAScript 5 ● Standard which JS is based on ● Version 5 ○ new objects, methods and properties ○ 'strict mode' ■ removes features ■ makes programs simpler and less error prone ■ backward compatible ■ 'use strict' once per scope ○ not yet supported ○ keep an eye out for the transition
  • 7. JSLint ● JavaScript ○ interpreted ○ no static compile-time checks = hard to debug ● Douglas Crockford ○ this tool "will hurt your feelings" ○ but also inspire confidence ● jslint.com ○ improve code quality ○ find syntax errors ○ find simple omissions ○ has a wide variety of settings: 'strict mode' compliance
  • 8. The Console ● present in most browsers ○ Gecko: Firebug ○ Webkit: Web Inspector ○ Trident: Developer Tools ● less obtrusive than alert() ● console's output methods ○ console.log() outputs params ○ console.dir() enumerates ○ type in directly
  • 9. Authoring Essentials ● Write Maintainable Code ○ readable ○ consistent ○ predictable ○ focused ○ documented ● Know Your Scope ○ local ○ global
  • 10. Global ● declared outside of any function ● browsers provide access via 'window' property ● shared among all code, including any 3rd party libs ● use as few as possible, strategies include: ○ namespaces ○ immediate functions ○ 'var' declarations
  • 11. Global ● 'var' declarations ○ var inside any function ■ "var foo = {}" ■ makes a foo object local to that function ■ "bar = {}" ■ adds a bar property to the global ■ "var nix = bix = 0" ■ makes a local nix and a global bix ○ var outside any function ■ makes a global variable (not a global property) ● 'var's CAN NOT be deleted, properties can ● ES5 strict mode throws error for undeclared variable assignments
  • 12. Variable Hoisting ● all var declarations in a function act as if declared at top ● so just declare them at top to avoid confusion var scope = "global"; function f(){ alert(scope); //undefined var scope = "local"; alert(scope); //local } f(); ____________________________ var scope = "global"; function f(){ var scope; alert(scope); //undefined scope = "local"; alert(scope); //local } f();
  • 13. Loops ● 'for' loop ○ cache the length value of your collection ■ Array ■ HTMLCollection ■ especially bad ■ live queries on the DOM ○ exception: when modifying length of collection ● try to avoid nested loops at all costs ○ look for other ways ○ ask around ○ might not be obvious, but worth it
  • 14. Loops ● 'for in' loops ○ enumeration of objects ■ ...technically can be used with arrays ■ ...but not recommended ○ hasOwnProperty() ■ important defensive strategy ■ filters out prototype chain ■ ...but has performance implication ■ if your object has redefined hasOwnProperty() ■ Object.prototype.hasOwnProperty.call(obj, i)
  • 15. Augmenting Built-ins ● it's done via 'prototype' ○ Object.prototype.newMethodForAll = function(){}; ● but it's best not done at all ○ less predictable ○ other devs won't get it ○ it will show up in loops that don't defend against it ● exception conditions - all 3 must be met! 1. if ES or JS will eventually implement anyway 2. if you are sure it doesn't already exist 3. you clearly document AND communicate to your team 4. example: Array.isArray