SlideShare une entreprise Scribd logo
1  sur  53
Télécharger pour lire hors ligne
Andreas Ecker | 1&1 Internet AG


Advanced Object-Oriented
JavaScript
These keywords belong too ...
                                                throws
abstract             extends          package
                                                transient
boolean              final            private
                                      protected volatile
byte                 float
char                 implements       public
class                import           short
const                int              static
double               interface        super
enum                 long             synchronized
export               native

Andreas Ecker | 1&1 Internet AG   page 2
... JavaScript !
    ECMAScript 3 / JavaScript 1.5
    Standard spezified in 1999
    Supported by all common browsers
    Many keywords reserved, but not used

    ECMAScript 4 / JavaScript 2.0
    Many new language features
    Not expected any time soon

Andreas Ecker | 1&1 Internet AG   page 3
Data Types


    Primitive Types

    Reference Types




Andreas Ecker | 1&1 Internet AG   page 4
Primitive Types
    Boolean                       true, false

    Number                        1, 3.141, -1.602e-19

    String                        quot;Joequot;

    null                          null

    undefined                     undefined



Andreas Ecker | 1&1 Internet AG   page 5
Reference Types
    Date                          new Date(1211623944453);

    Error                         new Error(quot;Oops!quot;);

    RegExp                        /^web.*$/i;

    Array                         [ quot;applequot;, quot;bananaquot; ]

    Function                      function(x) {return x*x}



Andreas Ecker | 1&1 Internet AG       page 6
Primitive                       Reference
                                               Date
  Types                           Types
     Boolean                                   Error

     Number                                   RegExp

       String                       Object

         null                                  Array

  undefined                                   Function


Andreas Ecker | 1&1 Internet AG    page 7
typeof
    Boolean                       quot;booleanquot;
    Number                        quot;numberquot;
    String                        quot;stringquot;
    null                                      Caution!
                                  quot;objectquot;
    undefined                     quot;undefinedquot;
    Array                                     Caution!
                                  quot;objectquot;
    Function                      quot;functionquot;
    Object                        quot;objectquot;

Andreas Ecker | 1&1 Internet AG   page 8
Object
unordered collection of properties with
arbitrary values
    object literal
    var obj = { name: quot;Joequot;, age: 26 };

    setting a property
    obj.lastName = quot;Smithquot;;

    retrieving properties
    alert(obj.name + quot; quot; + obj.lastName);

Andreas Ecker | 1&1 Internet AG   page 9
Object as Hash
Data structure that associates arbitrary
values with arbitrary strings
    property name as an identifier
    obj.lastName = quot;Smithquot;;

    property name as a string
    obj[quot;lastNamequot;] = quot;Smithquot;;

    for( prop in obj ) {
       alert( prop + quot;: quot; + obj[prop] );
    }
Andreas Ecker | 1&1 Internet AG   page 10
Class
Concept of a class does not exist...

... but use a function as a constructor:

                                            class “Dog”
    function Dog() {};

                                            instance “lassie”
    var lassie = new Dog;

    alert(lassie instanceof Dog); // true

Andreas Ecker | 1&1 Internet AG   page 11
Static Members
Because functions are „first-class objects“
we can attach properties:

    Class Variables
    Dog.SPECIES = quot;Canis lupusquot;;

    Class Methods
    Dog.getCount = function() {
       return Dog.COUNT;
    };

Andreas Ecker | 1&1 Internet AG   page 12
Instance Members
    Instance Variables

function Dog(name) {
   this.name = name;
};

var lassie = new Dog(quot;Lassiequot;);
alert( lassie.name );




Andreas Ecker | 1&1 Internet AG   page 13
Instance Members
    Instance Methods

function Dog(name) {
   this.name = name;
   this.bark =
     function() { alert(quot;Woof!quot;) };
};

var lassie = new Dog(quot;Lassiequot;);
lassie.bark();

Andreas Ecker | 1&1 Internet AG   page 14
Scope
    Global Scope

         Variables outside of any functions
     ●




         Variables inside functions without var
     ●




     var global1 = 1;
     global2 = 2;

     function foo() {
        global3 = 3;
     };
Andreas Ecker | 1&1 Internet AG   page 15
Scope
    Function Scope

         Variables inside functions declared with var
     ●




         Function arguments
     ●




     function foo(local1) {
        var local2 = 2;
     };



Andreas Ecker | 1&1 Internet AG   page 16
Scope
    Block Scope
... but can be faked:

// before block
(function() {
    // inside block

})();
// after block

Andreas Ecker | 1&1 Internet AG   page 17
Private Members
function Dog(name) {
   var _name = name; // private variable
   // privileged method
   this.getName = function() {
      return _name;
   };
};

var lassie = new Dog(quot;Lassiequot;);
alert( lassie.getName() );

Andreas Ecker | 1&1 Internet AG   page 18
Private Members
function Dog(name) {
   var _name = name;
   // private method
   var _fixName = function() {
      return _name.toUpperCase();
   };
   this.getName = function(){
      return _fixName();
   };
};
Andreas Ecker | 1&1 Internet AG   page 19
Closures
    Nested functions

    Inner function has still access to local
    variables even after the outer function
    has finished




Andreas Ecker | 1&1 Internet AG   page 20
Closures
function outer()
{
  var count = 1;
  function inner() { alert(count++) }
  return inner;
}

var myClosure = outer();
myClosure(); // ==> 1
myClosure(); // ==> 2

Andreas Ecker | 1&1 Internet AG   page 21
Inheritance (native)
                                            Pet
    function Pet() {};


    function Dog() {};


                                            Dog
    Dog.prototype = new Pet;




Andreas Ecker | 1&1 Internet AG   page 22
Calling the superclass' constructor
function Pet(name) {
   this.name = name;
};

function Dog(name) {
   // super(name)
   Pet.call( this, name );
   this.bark = function() {};
};

Dog.prototype = new Pet;
Andreas Ecker | 1&1 Internet AG   page 23
Calling a Method with Arbitrary Scope
Inside the method this now refers to the
scope you supplied:

    function foo() {
       this.bar();
    };

    foo.call( scope, arg1, arg2, ... );

    foo.apply( scope, [arg1, arg2, ...] );


Andreas Ecker | 1&1 Internet AG   page 24
Instance Members (improvement)
    // old: attach to quot;thisquot;
    function Dog(name) {
       this.bark =
           function(){ alert(quot;Woof!quot;) };
    };

    // new: attach to quot;prototypequot;
    function Dog(name) {};
    Dog.prototype.bark =
           function(){ alert(quot;Woof!quot;) };
    };

Andreas Ecker | 1&1 Internet AG   page 25
Prototype Chain                                                    undefined
                                                           no


                                   Pet                    found?     yes
                                                     no



                      Dog                     found?        yes
                                     no



lassie: Dog                       found?       yes




                 lassie.name

Andreas Ecker | 1&1 Internet AG     page 26
Instance vs. Prototype
    Property values on instance:
    local, instance-specific values

    Property values on prototype:
    read-only default values

Attaching to the prototype saves
memory, especially for large numbers
of instances


Andreas Ecker | 1&1 Internet AG   page 27
Class Augmentation
    Affects all new instances
    Affects all existing instances
    Allows modification of existing classes

String.prototype.trim =
  function() {
     return this.replace(/^s+/, quot;quot;);
  };

alert(quot;              Lassiequot;.trim() );

Andreas Ecker | 1&1 Internet AG   page 28
Overriding Methods
function Dog() {};
Dog.prototype.bark =
         function() { alert(quot;Woof!quot;) };

function Bulldog() {};
Bulldog.prototype = new Dog;

Bulldog.prototype.bark = function() {
  // super.bark();
  Dog.prototype.bark.call(this);
  alert(quot;Grrrh!!quot;) };
Andreas Ecker | 1&1 Internet AG   page 29
Abstract Class
function Pet() {
  if(this._id == Pet._id) {
    throw new Error(quot;No Pets, please!quot;);
  }
}
Pet._id = quot;Petquot;;
Pet.prototype._id = quot;Petquot;;

var fiffy = new Pet; // Error (intended)

Andreas Ecker | 1&1 Internet AG   page 30
Inheritance (improved)
But now our code to setup inheritance will fail:
Dog.prototype = new Pet;          // Error :-(

Solution: Do not create an instance of the actual
superclass just to setup inheritance, use a dummy:
function Dummy() {};
Dummy.prototype = Pet.prototype;

Dog.prototype = new Dummy;

Andreas Ecker | 1&1 Internet AG   page 31
Namespaces
if (typeof very == quot;undefinedquot;) {
   very = {};
}
if (typeof very.cute == quot;undefinedquot;) {
   very.cute = {};
}

very.cute.Dog = function() {};
var fiffy = new very.cute.Dog;


Andreas Ecker | 1&1 Internet AG   page 32
Singleton (“Essence”)
// The Last of the Mohicans
var chingachgook = {
   fight : function() {
     alert(quot;Woah!quot;);
   }
};

chingachgook.fight();



Andreas Ecker | 1&1 Internet AG   page 33
Singleton (“Ceremony”)
function Mohican() {
 this.fight = function(){alert(quot;Woah!quot;)}
};
Mohican.getInstance = function() {
   if (!this._instance) {
     this._instance = new this; }
   return this._instance;
};

Mohican.getInstance().fight();

Andreas Ecker | 1&1 Internet AG   page 34
Ceremony                              Essence




Andreas Ecker | 1&1 Internet AG   page 35
Ceremony                                   Essence




Andreas Ecker | 1&1 Internet AG   page 36
OO Wishlist
    Closed form of class declaration

    Namespaces

    Static members

    Instance members

    Inheritance

    Superclass call (constructor, overriden methods)


Andreas Ecker | 1&1 Internet AG   page 37
http://qooxdoo.org
   Open-Source JavaScript Framework


Andreas Ecker | 1&1 Internet AG   page 38
Class Declaration
qx.Class.define( quot;very.cute.Dogquot;, {
   extend: Dog,
   construct: function(name) {
     this.base( arguments, name); },
   statics: {
     SPECIES: quot;Canis lupus familiarisquot; },
   members: {
     bark: function() { alert(quot;wooofquot;);}}
} );


Andreas Ecker | 1&1 Internet AG   page 39
OO Wishlist (continued)
    Static class

    Abstract class

    Singleton




Andreas Ecker | 1&1 Internet AG   page 40
Static Class
qx.Class.define( quot;DogUtilquot;, {
  type: quot;staticquot;,
  statics: {
    SPECIES: quot;Canis lupusquot;,
    getCount: function() {}
  }
});




Andreas Ecker | 1&1 Internet AG   page 41
Abstract Class
qx.Class.define( quot;Petquot;, {
  type: quot;abstractquot;,
  construct: function(name) {
     this.name = name;
  },
  members: {
     getName: function() {
       return this.name; }
  }
});
Andreas Ecker | 1&1 Internet AG   page 42
Singleton
qx.Class.define( quot;Mohicanquot;, {
  type: quot;singletonquot;,
  members: {
    fight: function() {
      alert(quot;Woah!quot;);
    }
  }
});

var chingachgook = Mohican.getInstance()
chingachgook.fight();

Andreas Ecker | 1&1 Internet AG   page 43
OO Wishlist (continued)
    Destructors




Andreas Ecker | 1&1 Internet AG   page 44
Destructor
qx.Class.define( quot;very.cute.Dogquot;, {
  construct: function() {
     this._toys = new some.complex.Toy;
  },
  destruct: {
     this._disposeObjects(quot;_toysquot;);
  }
});



Andreas Ecker | 1&1 Internet AG   page 45
OO Wishlist (continued)
    Getters

    Setters




Andreas Ecker | 1&1 Internet AG   page 46
Dynamic Properties
qx.Class.define( quot;very.cute.Dogquot;, {
  properties: {
    name: { check: quot;Stringquot; }
  }
});

var fiffy = very.cute.Dog;
fiffy.setName(quot;Fiffyquot;);
alert( fiffy.getName() );

Andreas Ecker | 1&1 Internet AG   page 47
OO Wishlist (continued)
    Interfaces

    Definition of (empty) methods, that a class
    must implement individually


    Mixins

    Definition of (non-empty) methods, etc. that
    are added to an existing class

Andreas Ecker | 1&1 Internet AG   page 48
Interfaces
qx.Interface.define( quot;IVenomousquot;, {
  members: {
    actionToKill: function() {} }
});
qx.Class.define( quot;Snakequot;,
  implement: IVenomous,
  members: {
    actionToKill: function() {
      /* bite code here */ }
});
Andreas Ecker | 1&1 Internet AG   page 49
Mixins
qx.Mixin.define( quot;MMigrantquot;, {
  members: {
    leave: function() { /* code! */ },
    return: function() { /* code! */ },
  }
});

qx.Class.define( quot;Storkquot;,
  include: [MMigrant, MClattering]
});
Andreas Ecker | 1&1 Internet AG   page 50
Aspect-oriented Propramming (AOP)
Attach advices before or after each function call

qx.core.Aspect.addAdvice(
   quot;beforequot;, // or quot;afterquot;
   quot;*quot;,      // or quot;memberquot;, quot;staticquot;,
             // quot;constructorquot;,
             // quot;destructorquot;, quot;propertyquot;
   quot;your.namespace.*quot;, // regexp
   myAdvice
);
Andreas Ecker | 1&1 Internet AG   page 51
Aspect-oriented Propramming (AOP)
Signature of advice function:

myAdvice(
   fullName,                //    full function name
   target,                  //    function to call
   type,                    //    quot;beforequot; or quot;afterquot;
   args,                    //    arguments to target
   retValue                 //    only for quot;afterquot; advice
);

Andreas Ecker | 1&1 Internet AG     page 52
☺
Please try that at home

    http://qooxdoo.org
    qooxdoo: OO Documentation
    qooxdoo: API Viewer
    Crockford: JavaScript Survey
    Crockford: Private Members
    Flanagan: JavaScript (O'Reilly)
    andreas.ecker@1und1.de


Andreas Ecker | 1&1 Internet AG   page 53

Contenu connexe

Tendances

EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Nilesh Jayanandana
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 
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
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
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
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)AvitoTech
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
Unity 2018からのハイパフォーマンスな機能紹介
Unity 2018からのハイパフォーマンスな機能紹介Unity 2018からのハイパフォーマンスな機能紹介
Unity 2018からのハイパフォーマンスな機能紹介dena_genom
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architectureJung Kim
 
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
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 

Tendances (20)

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 
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...
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
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
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Unity 2018からのハイパフォーマンスな機能紹介
Unity 2018からのハイパフォーマンスな機能紹介Unity 2018からのハイパフォーマンスな機能紹介
Unity 2018からのハイパフォーマンスな機能紹介
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
 
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)
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 

En vedette

Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
General Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptGeneral Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptSpike Brehm
 
JavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly BracesJavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly BracesChicago ALT.NET
 
Douglas - Real JavaScript
Douglas - Real JavaScriptDouglas - Real JavaScript
Douglas - Real JavaScriptd0nn9n
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
JavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesJavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesSencha
 
03 Advanced JavaScript
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScriptYnon Perek
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Extending built in objects
Extending built in objectsExtending built in objects
Extending built in objectsMuhammad Ahmed
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpretedMartha Schumann
 
OOPS in javascript
OOPS in javascriptOOPS in javascript
OOPS in javascriptVijaya Anand
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript ConceptsNaresh Kumar
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript ApplicationAnis Ahmad
 
Node.js in action
Node.js in actionNode.js in action
Node.js in actionSimon Su
 

En vedette (20)

Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Java script basic
Java script basicJava script basic
Java script basic
 
Loops in java script
Loops in java scriptLoops in java script
Loops in java script
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
General Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptGeneral Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScript
 
JavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly BracesJavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly Braces
 
Douglas - Real JavaScript
Douglas - Real JavaScriptDouglas - Real JavaScript
Douglas - Real JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
JavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesJavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other Puzzles
 
03 Advanced JavaScript
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScript
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Array
ArrayArray
Array
 
Extending built in objects
Extending built in objectsExtending built in objects
Extending built in objects
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpreted
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
OOPS in javascript
OOPS in javascriptOOPS in javascript
OOPS in javascript
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript Concepts
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript Application
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 

Similaire à Advanced Object-Oriented JavaScript

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript BootcampAndreCharland
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015Igor Laborie
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascriptguest4d57e6
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)jeresig
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsBrian Moschel
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talkdesistartups
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Javascript do jeito certo
Javascript do jeito certoJavascript do jeito certo
Javascript do jeito certoAlexandre Gomes
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leetjohndaviddalton
 
0003 es5 핵심 정리
0003 es5 핵심 정리0003 es5 핵심 정리
0003 es5 핵심 정리욱래 김
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Alberto Naranjo
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVMJarek Ratajski
 

Similaire à Advanced Object-Oriented JavaScript (20)

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Javascript do jeito certo
Javascript do jeito certoJavascript do jeito certo
Javascript do jeito certo
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Javascript the New Parts
Javascript the New PartsJavascript the New Parts
Javascript the New Parts
 
0003 es5 핵심 정리
0003 es5 핵심 정리0003 es5 핵심 정리
0003 es5 핵심 정리
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
 

Dernier

7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...Paul Menig
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Dave Litwiller
 
HONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsHONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsMichael W. Hawkins
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
Understanding the Pakistan Budgeting Process: Basics and Key Insights
Understanding the Pakistan Budgeting Process: Basics and Key InsightsUnderstanding the Pakistan Budgeting Process: Basics and Key Insights
Understanding the Pakistan Budgeting Process: Basics and Key Insightsseri bangash
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 
Event mailer assignment progress report .pdf
Event mailer assignment progress report .pdfEvent mailer assignment progress report .pdf
Event mailer assignment progress report .pdftbatkhuu1
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsP&CO
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Centuryrwgiffor
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxAndy Lambert
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...Any kyc Account
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Neil Kimberley
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...anilsa9823
 
Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear RegressionRavindra Nath Shukla
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...lizamodels9
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxpriyanshujha201
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.Aaiza Hassan
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Serviceritikaroy0888
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMRavindra Nath Shukla
 

Dernier (20)

7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
HONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsHONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael Hawkins
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
Understanding the Pakistan Budgeting Process: Basics and Key Insights
Understanding the Pakistan Budgeting Process: Basics and Key InsightsUnderstanding the Pakistan Budgeting Process: Basics and Key Insights
Understanding the Pakistan Budgeting Process: Basics and Key Insights
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
Event mailer assignment progress report .pdf
Event mailer assignment progress report .pdfEvent mailer assignment progress report .pdf
Event mailer assignment progress report .pdf
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Century
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptx
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
 
Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear Regression
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Service
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSM
 

Advanced Object-Oriented JavaScript

  • 1. Andreas Ecker | 1&1 Internet AG Advanced Object-Oriented JavaScript
  • 2. These keywords belong too ... throws abstract extends package transient boolean final private protected volatile byte float char implements public class import short const int static double interface super enum long synchronized export native Andreas Ecker | 1&1 Internet AG page 2
  • 3. ... JavaScript ! ECMAScript 3 / JavaScript 1.5 Standard spezified in 1999 Supported by all common browsers Many keywords reserved, but not used ECMAScript 4 / JavaScript 2.0 Many new language features Not expected any time soon Andreas Ecker | 1&1 Internet AG page 3
  • 4. Data Types Primitive Types Reference Types Andreas Ecker | 1&1 Internet AG page 4
  • 5. Primitive Types Boolean true, false Number 1, 3.141, -1.602e-19 String quot;Joequot; null null undefined undefined Andreas Ecker | 1&1 Internet AG page 5
  • 6. Reference Types Date new Date(1211623944453); Error new Error(quot;Oops!quot;); RegExp /^web.*$/i; Array [ quot;applequot;, quot;bananaquot; ] Function function(x) {return x*x} Andreas Ecker | 1&1 Internet AG page 6
  • 7. Primitive Reference Date Types Types Boolean Error Number RegExp String Object null Array undefined Function Andreas Ecker | 1&1 Internet AG page 7
  • 8. typeof Boolean quot;booleanquot; Number quot;numberquot; String quot;stringquot; null Caution! quot;objectquot; undefined quot;undefinedquot; Array Caution! quot;objectquot; Function quot;functionquot; Object quot;objectquot; Andreas Ecker | 1&1 Internet AG page 8
  • 9. Object unordered collection of properties with arbitrary values object literal var obj = { name: quot;Joequot;, age: 26 }; setting a property obj.lastName = quot;Smithquot;; retrieving properties alert(obj.name + quot; quot; + obj.lastName); Andreas Ecker | 1&1 Internet AG page 9
  • 10. Object as Hash Data structure that associates arbitrary values with arbitrary strings property name as an identifier obj.lastName = quot;Smithquot;; property name as a string obj[quot;lastNamequot;] = quot;Smithquot;; for( prop in obj ) { alert( prop + quot;: quot; + obj[prop] ); } Andreas Ecker | 1&1 Internet AG page 10
  • 11. Class Concept of a class does not exist... ... but use a function as a constructor: class “Dog” function Dog() {}; instance “lassie” var lassie = new Dog; alert(lassie instanceof Dog); // true Andreas Ecker | 1&1 Internet AG page 11
  • 12. Static Members Because functions are „first-class objects“ we can attach properties: Class Variables Dog.SPECIES = quot;Canis lupusquot;; Class Methods Dog.getCount = function() { return Dog.COUNT; }; Andreas Ecker | 1&1 Internet AG page 12
  • 13. Instance Members Instance Variables function Dog(name) { this.name = name; }; var lassie = new Dog(quot;Lassiequot;); alert( lassie.name ); Andreas Ecker | 1&1 Internet AG page 13
  • 14. Instance Members Instance Methods function Dog(name) { this.name = name; this.bark = function() { alert(quot;Woof!quot;) }; }; var lassie = new Dog(quot;Lassiequot;); lassie.bark(); Andreas Ecker | 1&1 Internet AG page 14
  • 15. Scope Global Scope Variables outside of any functions ● Variables inside functions without var ● var global1 = 1; global2 = 2; function foo() { global3 = 3; }; Andreas Ecker | 1&1 Internet AG page 15
  • 16. Scope Function Scope Variables inside functions declared with var ● Function arguments ● function foo(local1) { var local2 = 2; }; Andreas Ecker | 1&1 Internet AG page 16
  • 17. Scope Block Scope ... but can be faked: // before block (function() { // inside block })(); // after block Andreas Ecker | 1&1 Internet AG page 17
  • 18. Private Members function Dog(name) { var _name = name; // private variable // privileged method this.getName = function() { return _name; }; }; var lassie = new Dog(quot;Lassiequot;); alert( lassie.getName() ); Andreas Ecker | 1&1 Internet AG page 18
  • 19. Private Members function Dog(name) { var _name = name; // private method var _fixName = function() { return _name.toUpperCase(); }; this.getName = function(){ return _fixName(); }; }; Andreas Ecker | 1&1 Internet AG page 19
  • 20. Closures Nested functions Inner function has still access to local variables even after the outer function has finished Andreas Ecker | 1&1 Internet AG page 20
  • 21. Closures function outer() { var count = 1; function inner() { alert(count++) } return inner; } var myClosure = outer(); myClosure(); // ==> 1 myClosure(); // ==> 2 Andreas Ecker | 1&1 Internet AG page 21
  • 22. Inheritance (native) Pet function Pet() {}; function Dog() {}; Dog Dog.prototype = new Pet; Andreas Ecker | 1&1 Internet AG page 22
  • 23. Calling the superclass' constructor function Pet(name) { this.name = name; }; function Dog(name) { // super(name) Pet.call( this, name ); this.bark = function() {}; }; Dog.prototype = new Pet; Andreas Ecker | 1&1 Internet AG page 23
  • 24. Calling a Method with Arbitrary Scope Inside the method this now refers to the scope you supplied: function foo() { this.bar(); }; foo.call( scope, arg1, arg2, ... ); foo.apply( scope, [arg1, arg2, ...] ); Andreas Ecker | 1&1 Internet AG page 24
  • 25. Instance Members (improvement) // old: attach to quot;thisquot; function Dog(name) { this.bark = function(){ alert(quot;Woof!quot;) }; }; // new: attach to quot;prototypequot; function Dog(name) {}; Dog.prototype.bark = function(){ alert(quot;Woof!quot;) }; }; Andreas Ecker | 1&1 Internet AG page 25
  • 26. Prototype Chain undefined no Pet found? yes no Dog found? yes no lassie: Dog found? yes lassie.name Andreas Ecker | 1&1 Internet AG page 26
  • 27. Instance vs. Prototype Property values on instance: local, instance-specific values Property values on prototype: read-only default values Attaching to the prototype saves memory, especially for large numbers of instances Andreas Ecker | 1&1 Internet AG page 27
  • 28. Class Augmentation Affects all new instances Affects all existing instances Allows modification of existing classes String.prototype.trim = function() { return this.replace(/^s+/, quot;quot;); }; alert(quot; Lassiequot;.trim() ); Andreas Ecker | 1&1 Internet AG page 28
  • 29. Overriding Methods function Dog() {}; Dog.prototype.bark = function() { alert(quot;Woof!quot;) }; function Bulldog() {}; Bulldog.prototype = new Dog; Bulldog.prototype.bark = function() { // super.bark(); Dog.prototype.bark.call(this); alert(quot;Grrrh!!quot;) }; Andreas Ecker | 1&1 Internet AG page 29
  • 30. Abstract Class function Pet() { if(this._id == Pet._id) { throw new Error(quot;No Pets, please!quot;); } } Pet._id = quot;Petquot;; Pet.prototype._id = quot;Petquot;; var fiffy = new Pet; // Error (intended) Andreas Ecker | 1&1 Internet AG page 30
  • 31. Inheritance (improved) But now our code to setup inheritance will fail: Dog.prototype = new Pet; // Error :-( Solution: Do not create an instance of the actual superclass just to setup inheritance, use a dummy: function Dummy() {}; Dummy.prototype = Pet.prototype; Dog.prototype = new Dummy; Andreas Ecker | 1&1 Internet AG page 31
  • 32. Namespaces if (typeof very == quot;undefinedquot;) { very = {}; } if (typeof very.cute == quot;undefinedquot;) { very.cute = {}; } very.cute.Dog = function() {}; var fiffy = new very.cute.Dog; Andreas Ecker | 1&1 Internet AG page 32
  • 33. Singleton (“Essence”) // The Last of the Mohicans var chingachgook = { fight : function() { alert(quot;Woah!quot;); } }; chingachgook.fight(); Andreas Ecker | 1&1 Internet AG page 33
  • 34. Singleton (“Ceremony”) function Mohican() { this.fight = function(){alert(quot;Woah!quot;)} }; Mohican.getInstance = function() { if (!this._instance) { this._instance = new this; } return this._instance; }; Mohican.getInstance().fight(); Andreas Ecker | 1&1 Internet AG page 34
  • 35. Ceremony Essence Andreas Ecker | 1&1 Internet AG page 35
  • 36. Ceremony Essence Andreas Ecker | 1&1 Internet AG page 36
  • 37. OO Wishlist Closed form of class declaration Namespaces Static members Instance members Inheritance Superclass call (constructor, overriden methods) Andreas Ecker | 1&1 Internet AG page 37
  • 38. http://qooxdoo.org Open-Source JavaScript Framework Andreas Ecker | 1&1 Internet AG page 38
  • 39. Class Declaration qx.Class.define( quot;very.cute.Dogquot;, { extend: Dog, construct: function(name) { this.base( arguments, name); }, statics: { SPECIES: quot;Canis lupus familiarisquot; }, members: { bark: function() { alert(quot;wooofquot;);}} } ); Andreas Ecker | 1&1 Internet AG page 39
  • 40. OO Wishlist (continued) Static class Abstract class Singleton Andreas Ecker | 1&1 Internet AG page 40
  • 41. Static Class qx.Class.define( quot;DogUtilquot;, { type: quot;staticquot;, statics: { SPECIES: quot;Canis lupusquot;, getCount: function() {} } }); Andreas Ecker | 1&1 Internet AG page 41
  • 42. Abstract Class qx.Class.define( quot;Petquot;, { type: quot;abstractquot;, construct: function(name) { this.name = name; }, members: { getName: function() { return this.name; } } }); Andreas Ecker | 1&1 Internet AG page 42
  • 43. Singleton qx.Class.define( quot;Mohicanquot;, { type: quot;singletonquot;, members: { fight: function() { alert(quot;Woah!quot;); } } }); var chingachgook = Mohican.getInstance() chingachgook.fight(); Andreas Ecker | 1&1 Internet AG page 43
  • 44. OO Wishlist (continued) Destructors Andreas Ecker | 1&1 Internet AG page 44
  • 45. Destructor qx.Class.define( quot;very.cute.Dogquot;, { construct: function() { this._toys = new some.complex.Toy; }, destruct: { this._disposeObjects(quot;_toysquot;); } }); Andreas Ecker | 1&1 Internet AG page 45
  • 46. OO Wishlist (continued) Getters Setters Andreas Ecker | 1&1 Internet AG page 46
  • 47. Dynamic Properties qx.Class.define( quot;very.cute.Dogquot;, { properties: { name: { check: quot;Stringquot; } } }); var fiffy = very.cute.Dog; fiffy.setName(quot;Fiffyquot;); alert( fiffy.getName() ); Andreas Ecker | 1&1 Internet AG page 47
  • 48. OO Wishlist (continued) Interfaces Definition of (empty) methods, that a class must implement individually Mixins Definition of (non-empty) methods, etc. that are added to an existing class Andreas Ecker | 1&1 Internet AG page 48
  • 49. Interfaces qx.Interface.define( quot;IVenomousquot;, { members: { actionToKill: function() {} } }); qx.Class.define( quot;Snakequot;, implement: IVenomous, members: { actionToKill: function() { /* bite code here */ } }); Andreas Ecker | 1&1 Internet AG page 49
  • 50. Mixins qx.Mixin.define( quot;MMigrantquot;, { members: { leave: function() { /* code! */ }, return: function() { /* code! */ }, } }); qx.Class.define( quot;Storkquot;, include: [MMigrant, MClattering] }); Andreas Ecker | 1&1 Internet AG page 50
  • 51. Aspect-oriented Propramming (AOP) Attach advices before or after each function call qx.core.Aspect.addAdvice( quot;beforequot;, // or quot;afterquot; quot;*quot;, // or quot;memberquot;, quot;staticquot;, // quot;constructorquot;, // quot;destructorquot;, quot;propertyquot; quot;your.namespace.*quot;, // regexp myAdvice ); Andreas Ecker | 1&1 Internet AG page 51
  • 52. Aspect-oriented Propramming (AOP) Signature of advice function: myAdvice( fullName, // full function name target, // function to call type, // quot;beforequot; or quot;afterquot; args, // arguments to target retValue // only for quot;afterquot; advice ); Andreas Ecker | 1&1 Internet AG page 52
  • 53. ☺ Please try that at home http://qooxdoo.org qooxdoo: OO Documentation qooxdoo: API Viewer Crockford: JavaScript Survey Crockford: Private Members Flanagan: JavaScript (O'Reilly) andreas.ecker@1und1.de Andreas Ecker | 1&1 Internet AG page 53