SlideShare a Scribd company logo
1 of 52
Download to read offline
Object Oriented JavaScript
            Mike Girouard — AJAXWorld 2009
Today’s Agenda
JavaScript Object Model
  Types, Constructors, Inheritance

“Missing” Features
  Namespaces,Visibility, Polymorphism

Useful Design Patterns
  Factories, Singletons, Modules


                      Mike Girouard — AJAXWorld 2009
The JavaScript Object
Model


         Mike Girouard — AJAXWorld 2009
Primitive Types
                                 Object



  Boolean        Number          String        Array       Date


  RegExp         Function         Math         Error     EvalError


 RangeError   ReferenceError   SyntaxError   TypeError   URIError




                            Mike Girouard — AJAXWorld 2009
Creating Custom Types

Object constructors are functions
Defining a new type is as simple as defining a
function
Creating a new instance is simply invoking a
function with the new prefix


                 Mike Girouard — AJAXWorld 2009
Creating Custom Types
// Define the constructor
var Timestamp = function () {
   this.value = new Date().getTime();
};

// Instantiate
var ts = new Timestamp;

// Read instance variable
console.log(ts.value);



                   Mike Girouard — AJAXWorld 2009
Instance Members

Instance members are defined in a constructor’s
prototype object
New instances will have access to prototype
members
Prototypes may be modified at runtime


                 Mike Girouard — AJAXWorld 2009
Instance Members
var Timestamp = function () {
   this.value = new Date().getTime();
};

Timestamp.prototype.getValue = function () {
   return this.value;
};

var ts = new Timestamp;
console.log(ts.getValue());



                   Mike Girouard — AJAXWorld 2009
Instance Members
var Timestamp = function () {
   this.value = new Date().getTime();
};

var ts = new Timestamp;

Timestamp.prototype.getValue = function () {
   return this.value;
};

console.log(ts.getValue()); // Still works


                   Mike Girouard — AJAXWorld 2009
Inheritance


         Mike Girouard — AJAXWorld 2009
Prototypal Inheritance

Completely eliminates the need for classes
Objects inherit directly from other objects
(prototypes)
Incredibly efficient, ridiculously strange



                  Mike Girouard — AJAXWorld 2009
Prototypal Inheritance
var Foo = function () {}; // Foo Constructor
var Bar = function () {}; // Bar Constructor
Bar.prototype = new Foo; // Bar extends Foo

var f = new Foo(); // Foo instance
var b = new Bar(); // Bar instance

console.log(f   instanceof   Foo);   //   true
console.log(f   instanceof   Bar);   //   false
console.log(b   instanceof   Foo);   //   true
console.log(b   instanceof   Bar);   //   true


                    Mike Girouard — AJAXWorld 2009
Classical Inheritance

JavaScript has no native support for classical
inheritance
Many libraries support class-like structures
Rolling your own is quite trivial



                  Mike Girouard — AJAXWorld 2009
Classical Inheritance
var Foo = classFactory({
  __construct: function () {
     this.identify();
  },

  identify: function () {
    console.log(‘Foo’);
  }
});




                  Mike Girouard — AJAXWorld 2009
Classical Inheritance

var Bar = Foo.extend({
  identify: function () {
    console.log(‘Bar’);
  }
});




                  Mike Girouard — AJAXWorld 2009
Classical Inheritance
var classFactory = function (obj, extends) {
  if (extends)
    for (var i in extends)
      if (!obj[i]) obj[i] = extends[i];

     if (obj.__construct) obj.__construct.call(obj);

  obj.extend = function (subclass) {
     return classFactory(subclass, obj);
  };

     return obj;
};

                     Mike Girouard — AJAXWorld 2009
“Missing” Features


         Mike Girouard — AJAXWorld 2009
Namespaces


        Mike Girouard — AJAXWorld 2009
Why bother?

JavaScript has implied global scope
Global variables are only for selfish people
Raise your hand if you use these variable names:
  id, element, name, value, target…




                 Mike Girouard — AJAXWorld 2009
Implementing namespaces

Use an object… any object
Remember:
  Objects can store any kind of value
  Everything is an object
  This means anything [mutable] can be a namespace



                      Mike Girouard — AJAXWorld 2009
Namespace Objects
var mikeg = {
  name : ‘Mike G’,
  location : ‘NYC’,

  getName : function () {
     return this.name;
  },
  getLocation : function () {
     return location;
  }
};


                  Mike Girouard — AJAXWorld 2009
Namespace Functions
var getXHR = function () {
  if (!getXHR.enabled) return null;

     var xhr = new XMLHttpRequest;
     getXHR.registry.push(xhr);

     return xhr;
};

getXHR.registry = [];
getXHR.enabled = true;


                     Mike Girouard — AJAXWorld 2009
Visibility


             Mike Girouard — AJAXWorld 2009
Data Hiding in JS

There is no concept of public, private, or
protected in JavaScript
Closures allow values to be remembered in a
function, even after it terminates



                  Mike Girouard — AJAXWorld 2009
Data Hiding in JS
var Person = function (name) {
    this.getName = function () {
       return name;
    };

     this.setName = function (newName) {
        return name = newName;
     };
};




                   Mike Girouard — AJAXWorld 2009
Data Hiding in JS
// Assume: Person

var mike = new Person(‘Mike G.’);
var alex = new Person(‘Alex H.’);

console.log(mike.name); // undefined
console.log(alex.name); // undefined

console.log(mike.getName()); // Mike G.
console.log(alex.getName()); // Alex H.



                    Mike Girouard — AJAXWorld 2009
Polymorphism


        Mike Girouard — AJAXWorld 2009
Easier than you think…

Because JavaScript is a dynamic language,
polymorphism is quite easy and very common.
Two common types of polymorphism:
 1. Runtime Replacement
 2. Loadtime Branching



                   Mike Girouard — AJAXWorld 2009
Loadtime Branching
var getXHR = function () {
  if (window.XMLHttpRequest) {
    return function () {
       // Return a standard XHR instance
    };
  }
  else {
    return function () {
       // Return an Explorer XHR instance
    };
  }
}(); // Note: parens trigger self-invocation

                  Mike Girouard — AJAXWorld 2009
Runtime Replacement
var documentListFactory = function () {
  var out = []; // Just a simple array

  // Override the default .push() method
  out.push = function (document) {
     Array.prototype.push.call(out, {
       document : document,
       timespamp : new Date().getTime()
     });
  };

     return out;
};

                   Mike Girouard — AJAXWorld 2009
Useful Design Patterns


         Mike Girouard — AJAXWorld 2009
Factories


            Mike Girouard — AJAXWorld 2009
You Need Factories
Forgetting the new keyword will break your
application.
The issue comes down to the implied global
scope
  Using new, context = the instance

  Forgetting new, context = window


                     Mike Girouard — AJAXWorld 2009
Brittle Constructor

var DocumentCreator = function (document) {
   // What does ‘this’ refer to?
   this.document = document;
};

new DocumentCreator(‘foo.txt’); // Instance
DocumentCreator(‘foo.txt’);     // window




                  Mike Girouard — AJAXWorld 2009
A Simple Factory
var DocumentCreator = function (document) {
   // Yes, constructors can have return values :)
   return DocumentCreator.factory(document);
};

DocumentCreator.factory = function (document) {
   return new DocumentCreator(document);
};

new DocumentCreator(‘foo.txt’); // Instance
DocumentCreator(‘foo.txt’);     // Instance


                   Mike Girouard — AJAXWorld 2009
Singletons


         Mike Girouard — AJAXWorld 2009
Singletons are Easy Too

Nothing more than a simple object literal
Objects are always passed by reference and
values are static
Very useful for grouping items together, even if
they exist in other objects


                  Mike Girouard — AJAXWorld 2009
Singletons

var myHttpLibrary = {
   newXHR : function (params) { ... },
   parseQueryString : function (qs) { ... },
   createQueryString : function (qs) { ... }
};




                   Mike Girouard — AJAXWorld 2009
The Module


        Mike Girouard — AJAXWorld 2009
A Visibility Pattern


Original pattern discovered by Douglas
Crockford
Simplifies private data in JS




                  Mike Girouard — AJAXWorld 2009
A Simple Module
var config = function () {
  var data = {};

  return {
     get : function (name) {
        return data[name];
     },
     set : function (name, value) {
        data[name] = value;
        return this.get(name);
     }
  };
}();

                   Mike Girouard — AJAXWorld 2009
A Simple Module

// Assume: config

config.set(‘name’, ‘Mike G.’);

console.log(config.data.name);   // undefined
console.log(config.get(‘name’)); // Mike G.




                    Mike Girouard — AJAXWorld 2009
A Better Module
var config = function () {
  var me, data = {};

  return me = {
     get : function (name) {
          return data[name]
     },
     set : function (name, value) {
        data[name] = value;
        return me.get(name);
     }
  };
}();

                   Mike Girouard — AJAXWorld 2009
Modules for Organization
var module = function () {
  var app, util, service;

  app = {};

  util = {};

  return service = {};
}();




                  Mike Girouard — AJAXWorld 2009
Modules for Organization
var module = function () {
  var app, util, service;

 app = {
    init : function () { ... }
 };

  util = {};

  return service = {
     init : app.init
  };
}();

                  Mike Girouard — AJAXWorld 2009
Any questions so far?


         Mike Girouard — AJAXWorld 2009
Miscellaneous…

Everything in JavaScript is an object
All objects can be enumerated via for…in
The for…in construct sees all the way up the
prototype chain
  myObject.hasOwnProperty(‘foo’)   is gross but necessary



                  Mike Girouard — AJAXWorld 2009
Miscellaneous…

Most primitives have literals
Primitive constructors aren’t called in literals
(IE: no prototype features added)
  Please don’t go modifying primitive prototypes




                      Mike Girouard — AJAXWorld 2009
Miscellaneous…

Forgetting to use the new keyword in some cases
will break your app.
The typeof operator is useful, but lies
The instanceof operator is more accurate



                  Mike Girouard — AJAXWorld 2009
Miscellaneous…

The use of this tempting, but introduces
ambiguity into your program
In most cases its not necessary and can be
avoided



                 Mike Girouard — AJAXWorld 2009
Miscellaneous…

Most of JavaScript’s OO features are clever
functional programming patterns
Studying functional programming languages will
make you a better JavaScript programmer



                 Mike Girouard — AJAXWorld 2009
Thank you.
             mikeg@lovemikeg.com

More Related Content

What's hot

Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan Dolgushin
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptLeonardo Borges
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Nilesh Jayanandana
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design PatternsDerek Brown
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 

What's hot (20)

Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 

Similar to Object Oriented JavaScript

Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Annotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsAnnotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsJames Kirkbride
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
The Power of the JVM: Applied Polyglot Projects with Java and JavaScript
The Power of the JVM: Applied Polyglot Projects with Java and JavaScriptThe Power of the JVM: Applied Polyglot Projects with Java and JavaScript
The Power of the JVM: Applied Polyglot Projects with Java and JavaScriptHazelcast
 

Similar to Object Oriented JavaScript (20)

Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Annotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsAnnotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark Arts
 
JavaScript
JavaScriptJavaScript
JavaScript
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
The Power of the JVM: Applied Polyglot Projects with Java and JavaScript
The Power of the JVM: Applied Polyglot Projects with Java and JavaScriptThe Power of the JVM: Applied Polyglot Projects with Java and JavaScript
The Power of the JVM: Applied Polyglot Projects with Java and JavaScript
 

More from Michael Girouard

Day to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerDay to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerMichael Girouard
 
JavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsJavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsMichael Girouard
 
JavaScript From Scratch: Events
JavaScript From Scratch: EventsJavaScript From Scratch: Events
JavaScript From Scratch: EventsMichael Girouard
 
JavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataJavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataMichael Girouard
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetMichael Girouard
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Michael Girouard
 
Learning To Love Java Script
Learning To Love Java ScriptLearning To Love Java Script
Learning To Love Java ScriptMichael Girouard
 
Learning To Love Java Script Color
Learning To Love Java Script ColorLearning To Love Java Script Color
Learning To Love Java Script ColorMichael Girouard
 

More from Michael Girouard (16)

Day to Day Realities of an Independent Worker
Day to Day Realities of an Independent WorkerDay to Day Realities of an Independent Worker
Day to Day Realities of an Independent Worker
 
Responsible JavaScript
Responsible JavaScriptResponsible JavaScript
Responsible JavaScript
 
Ajax for PHP Developers
Ajax for PHP DevelopersAjax for PHP Developers
Ajax for PHP Developers
 
JavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script ApplicationsJavaScript From Scratch: Writing Java Script Applications
JavaScript From Scratch: Writing Java Script Applications
 
JavaScript From Scratch: Events
JavaScript From Scratch: EventsJavaScript From Scratch: Events
JavaScript From Scratch: Events
 
JavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With DataJavaScript From Scratch: Playing With Data
JavaScript From Scratch: Playing With Data
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet Wet
 
Its More Than Just Markup
Its More Than Just MarkupIts More Than Just Markup
Its More Than Just Markup
 
Web Standards Evangelism
Web Standards EvangelismWeb Standards Evangelism
Web Standards Evangelism
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
A Look At Flex And Php
A Look At Flex And PhpA Look At Flex And Php
A Look At Flex And Php
 
Baking Cakes With Php
Baking Cakes With PhpBaking Cakes With Php
Baking Cakes With Php
 
Cfphp Zce 01 Basics
Cfphp Zce 01 BasicsCfphp Zce 01 Basics
Cfphp Zce 01 Basics
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
Learning To Love Java Script
Learning To Love Java ScriptLearning To Love Java Script
Learning To Love Java Script
 
Learning To Love Java Script Color
Learning To Love Java Script ColorLearning To Love Java Script Color
Learning To Love Java Script Color
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 

Object Oriented JavaScript

  • 1. Object Oriented JavaScript Mike Girouard — AJAXWorld 2009
  • 2. Today’s Agenda JavaScript Object Model Types, Constructors, Inheritance “Missing” Features Namespaces,Visibility, Polymorphism Useful Design Patterns Factories, Singletons, Modules Mike Girouard — AJAXWorld 2009
  • 3. The JavaScript Object Model Mike Girouard — AJAXWorld 2009
  • 4. Primitive Types Object Boolean Number String Array Date RegExp Function Math Error EvalError RangeError ReferenceError SyntaxError TypeError URIError Mike Girouard — AJAXWorld 2009
  • 5. Creating Custom Types Object constructors are functions Defining a new type is as simple as defining a function Creating a new instance is simply invoking a function with the new prefix Mike Girouard — AJAXWorld 2009
  • 6. Creating Custom Types // Define the constructor var Timestamp = function () { this.value = new Date().getTime(); }; // Instantiate var ts = new Timestamp; // Read instance variable console.log(ts.value); Mike Girouard — AJAXWorld 2009
  • 7. Instance Members Instance members are defined in a constructor’s prototype object New instances will have access to prototype members Prototypes may be modified at runtime Mike Girouard — AJAXWorld 2009
  • 8. Instance Members var Timestamp = function () { this.value = new Date().getTime(); }; Timestamp.prototype.getValue = function () { return this.value; }; var ts = new Timestamp; console.log(ts.getValue()); Mike Girouard — AJAXWorld 2009
  • 9. Instance Members var Timestamp = function () { this.value = new Date().getTime(); }; var ts = new Timestamp; Timestamp.prototype.getValue = function () { return this.value; }; console.log(ts.getValue()); // Still works Mike Girouard — AJAXWorld 2009
  • 10. Inheritance Mike Girouard — AJAXWorld 2009
  • 11. Prototypal Inheritance Completely eliminates the need for classes Objects inherit directly from other objects (prototypes) Incredibly efficient, ridiculously strange Mike Girouard — AJAXWorld 2009
  • 12. Prototypal Inheritance var Foo = function () {}; // Foo Constructor var Bar = function () {}; // Bar Constructor Bar.prototype = new Foo; // Bar extends Foo var f = new Foo(); // Foo instance var b = new Bar(); // Bar instance console.log(f instanceof Foo); // true console.log(f instanceof Bar); // false console.log(b instanceof Foo); // true console.log(b instanceof Bar); // true Mike Girouard — AJAXWorld 2009
  • 13. Classical Inheritance JavaScript has no native support for classical inheritance Many libraries support class-like structures Rolling your own is quite trivial Mike Girouard — AJAXWorld 2009
  • 14. Classical Inheritance var Foo = classFactory({ __construct: function () { this.identify(); }, identify: function () { console.log(‘Foo’); } }); Mike Girouard — AJAXWorld 2009
  • 15. Classical Inheritance var Bar = Foo.extend({ identify: function () { console.log(‘Bar’); } }); Mike Girouard — AJAXWorld 2009
  • 16. Classical Inheritance var classFactory = function (obj, extends) { if (extends) for (var i in extends) if (!obj[i]) obj[i] = extends[i]; if (obj.__construct) obj.__construct.call(obj); obj.extend = function (subclass) { return classFactory(subclass, obj); }; return obj; }; Mike Girouard — AJAXWorld 2009
  • 17. “Missing” Features Mike Girouard — AJAXWorld 2009
  • 18. Namespaces Mike Girouard — AJAXWorld 2009
  • 19. Why bother? JavaScript has implied global scope Global variables are only for selfish people Raise your hand if you use these variable names: id, element, name, value, target… Mike Girouard — AJAXWorld 2009
  • 20. Implementing namespaces Use an object… any object Remember: Objects can store any kind of value Everything is an object This means anything [mutable] can be a namespace Mike Girouard — AJAXWorld 2009
  • 21. Namespace Objects var mikeg = { name : ‘Mike G’, location : ‘NYC’, getName : function () { return this.name; }, getLocation : function () { return location; } }; Mike Girouard — AJAXWorld 2009
  • 22. Namespace Functions var getXHR = function () { if (!getXHR.enabled) return null; var xhr = new XMLHttpRequest; getXHR.registry.push(xhr); return xhr; }; getXHR.registry = []; getXHR.enabled = true; Mike Girouard — AJAXWorld 2009
  • 23. Visibility Mike Girouard — AJAXWorld 2009
  • 24. Data Hiding in JS There is no concept of public, private, or protected in JavaScript Closures allow values to be remembered in a function, even after it terminates Mike Girouard — AJAXWorld 2009
  • 25. Data Hiding in JS var Person = function (name) { this.getName = function () { return name; }; this.setName = function (newName) { return name = newName; }; }; Mike Girouard — AJAXWorld 2009
  • 26. Data Hiding in JS // Assume: Person var mike = new Person(‘Mike G.’); var alex = new Person(‘Alex H.’); console.log(mike.name); // undefined console.log(alex.name); // undefined console.log(mike.getName()); // Mike G. console.log(alex.getName()); // Alex H. Mike Girouard — AJAXWorld 2009
  • 27. Polymorphism Mike Girouard — AJAXWorld 2009
  • 28. Easier than you think… Because JavaScript is a dynamic language, polymorphism is quite easy and very common. Two common types of polymorphism: 1. Runtime Replacement 2. Loadtime Branching Mike Girouard — AJAXWorld 2009
  • 29. Loadtime Branching var getXHR = function () { if (window.XMLHttpRequest) { return function () { // Return a standard XHR instance }; } else { return function () { // Return an Explorer XHR instance }; } }(); // Note: parens trigger self-invocation Mike Girouard — AJAXWorld 2009
  • 30. Runtime Replacement var documentListFactory = function () { var out = []; // Just a simple array // Override the default .push() method out.push = function (document) { Array.prototype.push.call(out, { document : document, timespamp : new Date().getTime() }); }; return out; }; Mike Girouard — AJAXWorld 2009
  • 31. Useful Design Patterns Mike Girouard — AJAXWorld 2009
  • 32. Factories Mike Girouard — AJAXWorld 2009
  • 33. You Need Factories Forgetting the new keyword will break your application. The issue comes down to the implied global scope Using new, context = the instance Forgetting new, context = window Mike Girouard — AJAXWorld 2009
  • 34. Brittle Constructor var DocumentCreator = function (document) { // What does ‘this’ refer to? this.document = document; }; new DocumentCreator(‘foo.txt’); // Instance DocumentCreator(‘foo.txt’); // window Mike Girouard — AJAXWorld 2009
  • 35. A Simple Factory var DocumentCreator = function (document) { // Yes, constructors can have return values :) return DocumentCreator.factory(document); }; DocumentCreator.factory = function (document) { return new DocumentCreator(document); }; new DocumentCreator(‘foo.txt’); // Instance DocumentCreator(‘foo.txt’); // Instance Mike Girouard — AJAXWorld 2009
  • 36. Singletons Mike Girouard — AJAXWorld 2009
  • 37. Singletons are Easy Too Nothing more than a simple object literal Objects are always passed by reference and values are static Very useful for grouping items together, even if they exist in other objects Mike Girouard — AJAXWorld 2009
  • 38. Singletons var myHttpLibrary = { newXHR : function (params) { ... }, parseQueryString : function (qs) { ... }, createQueryString : function (qs) { ... } }; Mike Girouard — AJAXWorld 2009
  • 39. The Module Mike Girouard — AJAXWorld 2009
  • 40. A Visibility Pattern Original pattern discovered by Douglas Crockford Simplifies private data in JS Mike Girouard — AJAXWorld 2009
  • 41. A Simple Module var config = function () { var data = {}; return { get : function (name) { return data[name]; }, set : function (name, value) { data[name] = value; return this.get(name); } }; }(); Mike Girouard — AJAXWorld 2009
  • 42. A Simple Module // Assume: config config.set(‘name’, ‘Mike G.’); console.log(config.data.name); // undefined console.log(config.get(‘name’)); // Mike G. Mike Girouard — AJAXWorld 2009
  • 43. A Better Module var config = function () { var me, data = {}; return me = { get : function (name) { return data[name] }, set : function (name, value) { data[name] = value; return me.get(name); } }; }(); Mike Girouard — AJAXWorld 2009
  • 44. Modules for Organization var module = function () { var app, util, service; app = {}; util = {}; return service = {}; }(); Mike Girouard — AJAXWorld 2009
  • 45. Modules for Organization var module = function () { var app, util, service; app = { init : function () { ... } }; util = {}; return service = { init : app.init }; }(); Mike Girouard — AJAXWorld 2009
  • 46. Any questions so far? Mike Girouard — AJAXWorld 2009
  • 47. Miscellaneous… Everything in JavaScript is an object All objects can be enumerated via for…in The for…in construct sees all the way up the prototype chain myObject.hasOwnProperty(‘foo’) is gross but necessary Mike Girouard — AJAXWorld 2009
  • 48. Miscellaneous… Most primitives have literals Primitive constructors aren’t called in literals (IE: no prototype features added) Please don’t go modifying primitive prototypes Mike Girouard — AJAXWorld 2009
  • 49. Miscellaneous… Forgetting to use the new keyword in some cases will break your app. The typeof operator is useful, but lies The instanceof operator is more accurate Mike Girouard — AJAXWorld 2009
  • 50. Miscellaneous… The use of this tempting, but introduces ambiguity into your program In most cases its not necessary and can be avoided Mike Girouard — AJAXWorld 2009
  • 51. Miscellaneous… Most of JavaScript’s OO features are clever functional programming patterns Studying functional programming languages will make you a better JavaScript programmer Mike Girouard — AJAXWorld 2009
  • 52. Thank you. mikeg@lovemikeg.com