Introduction to Object Oriented Javascript

Embed Size (px)

Citation preview

  • 8/11/2019 Introduction to Object Oriented Javascript

    1/62

    An Introduction

  • 8/11/2019 Introduction to Object Oriented Javascript

    2/62

    Basic Topics

    Namespaces

    Classes

    Encapsulation

    Inheritance

    Interfaces

    Advanced Topics

    Singleton Pattern Static

    Attributes/Methods

    SolutionEncapsulation

    JavaScript Build

    Overview

  • 8/11/2019 Introduction to Object Oriented Javascript

    3/62

    JavaScript does not support many of the typical object oriented featuresfound in other languages. However JavaScript is powerful enough to createthese features on top of the language.

    Here is a list of types JavaScript supports:

    vara =true; //boolean

    varb =1; //numeric

    varc ='Ben'; //string

    vard =[]; //arraysvare ={}; //objects

    varf =function() { ... }; //functions

    Introduction

  • 8/11/2019 Introduction to Object Oriented Javascript

    4/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    5/62

    Namespaces in JavaScript are simply a collection of nested objects that holdonto references to class constructors.

    //we start by declaring the root namespace

    varninemsn =window.ninemsn ||{};

    //then we can declare sub namespaces

    ninemsn.portal =ninemsn.portal ||{};

    ninemsn.portal.thirdparty =ninemsn.portal.thirdparty ||{};

    //add some classes to the namespace

    ninemsn.portal.thirdparty.Api =function() { ... };

    ninemsn.portal.thirdparty.Config =function() { ... };

    Namespaces

  • 8/11/2019 Introduction to Object Oriented Javascript

    6/62

    Be defensive, always check to see if a namespace already exists. Here is why:

    //somewhere at the top of the page

    ninemsn.portal.ads =ninemsn.portal.ads ||{}

    ...

    //a bit further downninemsn.portal.omniture =ninemsn.portal.omniture ||{};

    ...

    //a bit further down

    ninemsn.portal.video =ninemsn.portal.video ||{};

    //and even further down some code which clears the ninemsn namespace

    varninemsn ={}; //never do this!

    Namespaces

  • 8/11/2019 Introduction to Object Oriented Javascript

    7/62

    Avoid using the global namespace. If you need some temporary work spaceuse self executing functions:

    //instead of this

    vartoday =newDate();

    varfriendlyDate = today.getDate() +'/'

    +today.getMonth() +'/'+today.getgetFullYear();

    $('#year').html(friendlyDate);

    //do this

    (function() {

    vartoday =newDate();

    varfriendlyDate =today.getDate() +'/'

    +today.getMonth() +'/'+today.getgetFullYear();

    $('#year').html(friendlyDate);

    }());

    Namespaces

  • 8/11/2019 Introduction to Object Oriented Javascript

    8/62

    The Global namespace:

    Treat it like a public toilet. You can't avoid it, but whileyou're there have the least contact possible: you have noidea who has been here, or what they've done, and no ideawho and what will come after.

    - Dmitry Baranovskiy

    Namespaces

  • 8/11/2019 Introduction to Object Oriented Javascript

    9/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    10/62

    To create a class we build a class constructor function. When this function iscalled it returns a new instance of the class.

    How this constructor function constructs the instance can vary. There aretwo main methods:

    Creating instances dynamically

    Creating instances using the Prototype

    What's the difference between the two?

    Classes

  • 8/11/2019 Introduction to Object Oriented Javascript

    11/62

    Classes

    Instance 1

    Method 1

    Method 2

    Method 3

    Attribute 1

    Attribute 2

    Instance 2

    Method 1

    Method 2

    Method 3

    Attribute 1

    Attribute 2

    Instance 3

    Method 1

    Method 2

    Method 3

    Attribute 1

    Attribute 2

    Instance 4

    Method 1

    Method 2

    Method 3

    Attribute 1

    Attribute 2

    Dynamic Class Creation

  • 8/11/2019 Introduction to Object Oriented Javascript

    12/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    13/62

    Allows for encapsulation

    Inheritance behaviour issimilar to most serverside languages

    Is simple to implement

    Does not perform as well

    as the prototype methoddue to additionalmemory consumption

    Breaks the instanceofmethod when usinginheritance (however the

    use of interfaces makesthis less of an issue)

    Pros

    Cons

    ClassesDynamic Class Creation

  • 8/11/2019 Introduction to Object Oriented Javascript

    14/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    15/62

    Classes

    1 10 100 1000 10000 100000 1000000

    Prototype 0 0 0 1 7 60 650

    Dynamic 0 0 1 2 34 258 3592

    0

    500

    1000

    1500

    2000

    2500

    3000

    3500

    4000

    Execution Time (ms)

  • 8/11/2019 Introduction to Object Oriented Javascript

    16/62

    Classes

    1 10 100 1000 10000 100000 1000000

    Prototype 1.64 1.64 1.64 1.7 2.32 8.9 75.15

    Dynamic 1.63 1.64 1.69 2.12 6.48 50.41 527.22

    0

    100

    200

    300

    400

    500

    600

    Memory Consumption (MB)

  • 8/11/2019 Introduction to Object Oriented Javascript

    17/62

    varMan =function() {

    this.changeMood =function(mood) { ... };

    this.speak =function(text) { ... };

    this.wave =function() { ... };

    this.wink =function() { ... };

    };

    varben =newMan();

    ben.speak('Hello');

    ben.wave();

    Classes

  • 8/11/2019 Introduction to Object Oriented Javascript

    18/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    19/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    20/62

    Encapsulation is achieved using a feature of JavaScript called closures.

    What is a closure?

    A closure is the local variables for a function - kept alive afterthe function

    has returned

    A closure is a stack-frame which is not de-allocatedwhen the functionreturns (as if a 'stack-frame' were malloc'ed instead of being on thestack!).

    Encapsulation

  • 8/11/2019 Introduction to Object Oriented Javascript

    21/62

    An example of a closure:

    functionsayHello(name) {

    vartext ='Hello '+name; // local variable

    returnfunction() { alert(text); };}

    varsay =sayHello('Ben');

    say(); //Hello Ben

    Encapsulation

  • 8/11/2019 Introduction to Object Oriented Javascript

    22/62

    varMan =function(location) {

    //private constants

    var_MARKUP ='{html markup goes here}';

    //private attributes

    var_root;

    //public methods

    this.changeMood =function(mood) { ... };

    ...

    //instance constructor

    _root =$(location);

    _root.html(_MARKUP); //render the man

    };

    Encapsulation

  • 8/11/2019 Introduction to Object Oriented Javascript

    23/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    24/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    25/62

    Inheritance is implemented by a child class calling the constructor of itsparent. The scope of the child is passed to the parent.

    varParent =function() {

    this.methodA =function() { ... };

    this.methodB =function() { ... };

    };

    varChild =function() {

    Parent.call(this); //pass the parent the scope of the child

    this.methodC =function() { ... };

    };

    varinstance =newChild();

    instance.methodA();

    Inheritance

  • 8/11/2019 Introduction to Object Oriented Javascript

    26/62

    varParent =function() {

    this.methodA =function() { ... };

    };

    varChild =function() {

    Parent.call(this);

    var_base ={ methodA:this.methodA };

    this.methodA =function() {

    _base.methodA();

    //do additional stuff

    };

    this.methodB =function() { ... }

    };

    Inheritance

  • 8/11/2019 Introduction to Object Oriented Javascript

    27/62

    Inheritance

  • 8/11/2019 Introduction to Object Oriented Javascript

    28/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    29/62

    Interfaces are implemented using a concept called Duck Typing.

    Duck Typing:

    When I see a bird that walks like a duck and swims like a duck and quacks like a

    duck, I call that bird a duck.- James Whitcomb Riley

    An interface is a list of function names. An object implements the interface if

    it has all the functions in the list.

    A helper class is used to centralise the checking.

    Interfaces

  • 8/11/2019 Introduction to Object Oriented Javascript

    30/62

    //declare the interface

    varIPerson =newInterface('IPerson',

    ['changeMood','speak','wave','wink']);

    //declare the class

    varMan =function() { ... }; //implements IPerson

    //create the instance

    varben =newMan();

    //ensure the object implements the interface

    Interface.ensureImplements(ben,IPerson);

    Interfaces

  • 8/11/2019 Introduction to Object Oriented Javascript

    31/62

    Interfaces

  • 8/11/2019 Introduction to Object Oriented Javascript

    32/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    33/62

    Is useful when you only want to guarantee only one instance of your classexists, e.g. API or Configuration objects.

    Works by hiding the constructor function in a closure and never exposing itto the rest of the page.

    Can be implemented in two ways:

    1. Automatic loading

    2. Lazy loading

    CAVEAT: This pattern breaks inheritance.

    Singleton Pattern

  • 8/11/2019 Introduction to Object Oriented Javascript

    34/62

    Automatic Loading

    varPersonFactory =function() {

    functionconstructor() {

    this.getPerson =function(location) { ... }

    };

    returnnewconstructor();

    } ();

    varfactory =newPersonFactory(); //TypeError: PersonFactory is not a constructor

    varperson1 =PersonFactory.getPerson('#world');

    Singleton Pattern

  • 8/11/2019 Introduction to Object Oriented Javascript

    35/62

    Lazy LoadingvarPersonFactory =function() {

    var_instance;

    functionconstructor() {

    this.getPerson =function(location) { ... }

    };

    return{

    getInstance:function() {

    return_instance ||(_instance =newconstructor());

    }

    };

    } ();

    varperson1 = PersonFactory.getInstance().getPerson('#world');

    Singleton Pattern

  • 8/11/2019 Introduction to Object Oriented Javascript

    36/62

    The Singleton Pattern

  • 8/11/2019 Introduction to Object Oriented Javascript

    37/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    38/62

    Not all attributes and methods need to be attached to every single instance.We can improve performance by making these things static.

    Some common situations where this would be applicable:

    You have a method that does not need access to the instance You have a method which does need access to the instance, but the value

    needed can be passed in as a parameter

    You have an attribute which is constant

    Static attributes and methods are implemented by wrapping the constructorwith a function in order to create a closure where the static items can live.

    Static Attributes/Methods

  • 8/11/2019 Introduction to Object Oriented Javascript

    39/62

    varClass =function() {

    var_PRIVATE_CONSTANT_VALUE ='{something important}';

    functionprivateStaticMethod() {

    //something useful

    };

    functionconstructor() {

    this.publicMethod =function() {

    privateStaticMethod();

    ...};

    };

    returnconstructor;

    } ();

    Static Attributes/Methods

  • 8/11/2019 Introduction to Object Oriented Javascript

    40/62

    varClass =function() {functionconstructor() {

    this.publicMethod =function() {

    constructor.publicStaticMethod();

    ...

    };

    };

    constructor.publicStaticMethod =function() { ... };

    returnconstructor;

    } ();

    Class.publicStaticMethod();

    Static Attributes/Methods

  • 8/11/2019 Introduction to Object Oriented Javascript

    41/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    42/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    43/62

    Static Attributes/Methods

  • 8/11/2019 Introduction to Object Oriented Javascript

    44/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    45/62

    Encapsulation at a class level is a great way of hiding the inner workings of aclass, but sometimes we want to hide the inner workings of a solution.

    Usually only a small number of classes need to be accessible, the rest canremain hidden in a closure.

    This forces all users of a solution to interact in the intended way.

    Refactoring is greatly simplified as there is now a guarantee that no externalcode is dependant on the internal solution classes.

    Solution Encapsulation

  • 8/11/2019 Introduction to Object Oriented Javascript

    46/62

    (function(demos) {varIPerson =newInterface(...);

    varMoodType ={ ... };

    varPerson =function() { ... };

    varMan =function() { ... };

    varWoman =function() { ... };

    varPersonFactory =function() { ... };

    //expose public objects

    demos.demo6.MoodType =MoodType;

    demos.demo6.PersonFactory =PersonFactory;

    } (demos));

    Solution Encapsulation

  • 8/11/2019 Introduction to Object Oriented Javascript

    47/62

    Solution Encapsulation

  • 8/11/2019 Introduction to Object Oriented Javascript

    48/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    49/62

    Keeping each class in its own file makes big solutions easy to maintain, butwe dont want to include each file individually on the page.

    We can use MS Build to combine all files in a solution into a single file for useon the page.

    We can also use MS Build to minify this single combined file to reduce thefile size.

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    50/62

    Add version to the file name

    Minify the combined file into a minified file

    Merge the individual files into a combined file

    Declare the list of files to be minified

    Clear any readonly flags on the output files

    Declare variables (such as the path to the minified file, solution version etc)

    JavaScript BuildMS Build is an XML file containing instructions telling the builder what to do.The JavaScript build is broken down into the following steps:

  • 8/11/2019 Introduction to Object Oriented Javascript

    51/62

    Declare variables (such as the path to the minified file, solution version etc):

    demo7

    1.0.0

    $(SourceLocation)js\demo7\code\version.js

    $(SourceLocation)js\demo7\$(Project)-latest.js

    $(SourceLocation)js\demo7\$(Project)-latest.min.js

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    52/62

    Clear any read-only flags on the output files:

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    53/62

    Declare the list of files to be minified:

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    54/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    55/62

  • 8/11/2019 Introduction to Object Oriented Javascript

    56/62

    Add version to the file name:

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    57/62

    We can also use MS Build to help with Solution Encapsulation.

    Solution Encapsulation is essentially a wrapper around the entire solution.

    We can build the solution as individual files and merge them together.Consider this single file to be our solution.

    We can then create a file which is the wrapper. This wrapper encapsulatesthe solution, so we need to take the solution file and place it into thiswrapper.

    The wrapper defines a placeholder so MS Build knows where to place thesolution.

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    58/62

    Howeverwhat about the namespaces?

    The individual classes attach themselves to the public namespace. By doingthis our solution encapsulation is bypassed.

    This can be fixed by the wrapper. It can declare two namespaces, a publicone visible to everyone, and a private one visible to only classes within thesolution.

    All classes attach themselves to the private namespace. The wrapper thenselectively exposes the classes which should be public.

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    59/62

    (function() {

    vardemosExternal =window.demos;

    vardemos ={};

    demos.demo7 ={};

    {library}

    //expose public objects

    demosExternal.demo7.MoodType =demos.demo7.MoodType;

    demosExternal.demo7.PersonFactory =demos.demo7.PersonFactory;

    } ());

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    60/62

    JavaScript Build

  • 8/11/2019 Introduction to Object Oriented Javascript

    61/62

    Basic Topics

    Namespaces Classes

    Encapsulation

    Inheritance

    Interfaces

    Advanced Topics

    Singleton Pattern Static

    Attributes/Methods

    SolutionEncapsulation

    JavaScript Build

    Summary

  • 8/11/2019 Introduction to Object Oriented Javascript

    62/62