SlideShare a Scribd company logo
1 of 20
JavaScript Classes &
    Inheritance
      Marc Heiligers
      @marcheiligers
Basic JS Classes

Functions act as constructors
Functions have a prototype
Use new to create an instance of a type
Call instance methods with dot notation
function Animal() {
  this.name = "animal";
}

Animal.prototype.speak = function() {
   console.log("I'm a " + this.name);
};

var animal = new Animal();
animal.speak(); //logs "I'm a animal"
Object
All JS objects inherit from Object
Object has 2 standard methods:
    toString
    valueOf
Lot’s of non-standard and newer methods:
    https://developer.mozilla.org/en/JavaScript/Reference/
    Global_Objects/Object
Overriding Methods

Can override super class methods by:
   attaching new methods to the prototype property
   eg. Animal.prototype.toString = function() { ... }
console.log(animal.toString()); //logs "[object Object]"

Animal.prototype.toString = function() {
   return "[" + this.name + " Animal]";
};

console.log(animal.toString()); //logs "[animal Animal]"

console.log(animal.valueOf()); //logs Animal { name="animal",
↳speak=function(), toString=function()}

console.log("" + animal.valueOf()); //logs "[animal Animal]"

Animal.prototype.valueOf = function() {
   return this.name;
};

console.log(animal.valueOf()); //logs "animal"
Add methods to existing Classes
Add methods to the prototype of the existing class
All instances of the class will get those methods
You can extend built in classes too - with a couple of caveats
   Generally bad to extend the prototype of Object
   Generally accepted as bad to extend the prototype of
   DOM classes, although MooTools and Prototype do this
String.prototype.articulize = function() {
   if(["a", "e", "i", "o", "u"].indexOf(this[0].toLowerCase())
    ↳ >= 0) {
     return "an " + this;
   } else {
     return "a " + this;
   }
};

console.log("Pig".articulize()); // logs "a Pig"
console.log("Elephant".articulize()); // logs "an Elephant"

Animal.prototype.speak = function() {
   console.log("I'm " + this.name.articulize());
};
animal.speak(); //logs "I'm an animal"
Inheritance

Create a new constructor function
Assign a new instance of the base class to the prototype
   function A { ... }
   function B { ... }
   B.prototype = new A;
function Pig() {
  this.name = "pig";
}
Pig.prototype = new Animal;
var pig = new Pig();
pig.speak(); // logs "I'm a pig"
console.log(pig.toString()); // logs "[pig Animal]"

Animal.prototype.countLegs = function() {
   return this.legs || 0;
};
Pig.prototype.legs = 4;

console.log(animal.valueOf() + " has " + animal.countLegs() +
↳" legs"); // logs "animal has 0 legs";

console.log(pig.valueOf() + " has " + pig.countLegs() +
↳" legs"); // logs "pig has 4 legs";
function Eisbein() {
  this.legs = 1; // Instance variable
}
Eisbein.prototype = new Pig;

var eisbein = new Eisbein();
eisbein.speak(); // logs "I'm a pig"

console.log(eisbein.valueOf() + " has " +
↳eisbein.countLegs() + " legs");
↳// logs "pig has 1 legs";
Calling base class methods
Use Function#call to call the base class method in the context
of the current class
   Base.prototype.method.call(this);
Call is useful in many other places too
   Array.prototype.slice.call(arguments); //creates a real
   array from the arguments oject
Pig.prototype.speak = function() {
   Animal.prototype.speak.call(this);
   console.log("Snork");
};

pig.speak(); // logs "I'm a pignSnork"

Eisbein.prototype.speak = function() {
   Pig.prototype.speak.call(this);
   console.log("Sizzle");
};

eisbein.speak();
↳// logs "I'm a pignSnorknSizzle"
Making it Classical

Create a Class object to create classes
   make it look more like classical inheritance
   have easier access to super class methods
(function(global) {
  var isFn = function(fn) {
     return typeof fn == "function";
  };

  global.Class = function() {};
  global.Class.create = function(superClass) {
    var klass = function(magic) {
       // call init only if there's no magic cookie
       if(magic != isFn && isFn(this.init)) {
         this.init.apply(this, arguments);
       }
    };

    klass.prototype = new this(isFn);

    for(key in superClass) {
      (function(fn, superFn) { // create a closure
        k.prototype[key] = !isFn(fn) || !isFn(superFn) ? fn :
          function() {
             this.super = sfn;
             return fn.apply(this, arguments);
          };
      })(superClass[key], k.prototype[key]);
    }

    klass.prototype.constructor = klass;
    klass.extend = this.extend || this.create;

    return klass;
  };
})(this);
(function(global) {
  var isFn = function(fn) {
     return typeof fn == "function";
  };

  global.Class = function() {};
  global.Class.create = function(derived) {
    var klass = function(magic) {
       // call init only if there's no magic cookie
       if(magic != isFn && isFn(this.init)) {
         this.init.apply(this, arguments);
       }
    };
// use our private method as magic cookie
    klass.prototype = new this(isFn);

   for(key in derived) {
     (function(fn, superFn) { // create a closure
       klass.prototype[key] = !isFn(fn) || !isFn(superFn) ?
         fn :
         function() {
            this.super = superFn;
            return fn.apply(this, arguments);
         };
     })(derived[key], klass.prototype[key]);
   }

   klass.prototype.constructor = klass;
   klass.extend = this.extend || this.create;

    return klass;
  };
})(this);
var Animal = Class.create({
  init: function() {
     this.name = "animal";
  },
  speak: function() {
     console.log("I'm " + this.name.articulize());
  },
  toString: function() {
     return "[" + this.name + " Animal]";
  },
  valueOf: function() {
     return this.name;
  }
});

var animal = new Animal();
animal.speak(); // logs "I'm an animal"
console.log(animal.toString()); // logs [animal Animal]
console.log(animal.valueOf()); // logs animal
var Pig = Animal.extend({
  init: function() {
     this.name = "Pig";
  },
  speak: function() {
     this.super();
     console.log("Snork");
  }
});

var Eisbein = Pig.extend({
  speak: function() {
    this.super();
    console.log("Sizzle");
  }
});

var pig = new Pig();
pig.speak(); // logs "I'm a pignSnork"

var eisbein = new Eisbein();
eisbein.speak(); // logs "I'm a pignSnorknSizzle"
Questions?

More Related Content

What's hot

連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
Doctrineのメモリーリークについて
DoctrineのメモリーリークについてDoctrineのメモリーリークについて
Doctrineのメモリーリークについてt satoppejp
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee confIgor Anishchenko
 
What's New in PHP 5.5
What's New in PHP 5.5What's New in PHP 5.5
What's New in PHP 5.5Corey Ballou
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorFedor Lavrentyev
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overviewSteve Min
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to knowTomasz Dziurko
 

What's hot (20)

連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
Doctrineのメモリーリークについて
DoctrineのメモリーリークについてDoctrineのメモリーリークについて
Doctrineのメモリーリークについて
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
ES6
ES6ES6
ES6
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
Perl
PerlPerl
Perl
 
What's New in PHP 5.5
What's New in PHP 5.5What's New in PHP 5.5
What's New in PHP 5.5
 
Google guava
Google guavaGoogle guava
Google guava
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Linq introduction
Linq introductionLinq introduction
Linq introduction
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
EMFPath
EMFPathEMFPath
EMFPath
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 
Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 

Similar to JavaScript Classes and Inheritance

Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Lukas Ruebbelke
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesRobert Nyman
 
Coding using jscript test complete
Coding using jscript test completeCoding using jscript test complete
Coding using jscript test completeViresh Doshi
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival GuideGiordano Scalzo
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J ScriptRoman Agaev
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: PrototypesVernon Kesner
 
JSDay Italy - Backbone.js
JSDay Italy - Backbone.jsJSDay Italy - Backbone.js
JSDay Italy - Backbone.jsPierre Spring
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new featuresGephenSG
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScriptryanstout
 
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScriptBrian Moschel
 
Soundreader.classpathSoundreader.project Soundre.docx
Soundreader.classpathSoundreader.project  Soundre.docxSoundreader.classpathSoundreader.project  Soundre.docx
Soundreader.classpathSoundreader.project Soundre.docxwhitneyleman54422
 

Similar to JavaScript Classes and Inheritance (20)

Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of Chocolates
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Coding using jscript test complete
Coding using jscript test completeCoding using jscript test complete
Coding using jscript test complete
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival Guide
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J Script
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
JSDay Italy - Backbone.js
JSDay Italy - Backbone.jsJSDay Italy - Backbone.js
JSDay Italy - Backbone.js
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
 
Class
ClassClass
Class
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
 
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScript
 
JavaScript patterns
JavaScript patternsJavaScript patterns
JavaScript patterns
 
Soundreader.classpathSoundreader.project Soundre.docx
Soundreader.classpathSoundreader.project  Soundre.docxSoundreader.classpathSoundreader.project  Soundre.docx
Soundreader.classpathSoundreader.project Soundre.docx
 
Prototypes
PrototypesPrototypes
Prototypes
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 

Recently uploaded

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 

Recently uploaded (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

JavaScript Classes and Inheritance

  • 1. JavaScript Classes & Inheritance Marc Heiligers @marcheiligers
  • 2. Basic JS Classes Functions act as constructors Functions have a prototype Use new to create an instance of a type Call instance methods with dot notation
  • 3. function Animal() { this.name = "animal"; } Animal.prototype.speak = function() { console.log("I'm a " + this.name); }; var animal = new Animal(); animal.speak(); //logs "I'm a animal"
  • 4. Object All JS objects inherit from Object Object has 2 standard methods: toString valueOf Lot’s of non-standard and newer methods: https://developer.mozilla.org/en/JavaScript/Reference/ Global_Objects/Object
  • 5. Overriding Methods Can override super class methods by: attaching new methods to the prototype property eg. Animal.prototype.toString = function() { ... }
  • 6. console.log(animal.toString()); //logs "[object Object]" Animal.prototype.toString = function() { return "[" + this.name + " Animal]"; }; console.log(animal.toString()); //logs "[animal Animal]" console.log(animal.valueOf()); //logs Animal { name="animal", ↳speak=function(), toString=function()} console.log("" + animal.valueOf()); //logs "[animal Animal]" Animal.prototype.valueOf = function() { return this.name; }; console.log(animal.valueOf()); //logs "animal"
  • 7. Add methods to existing Classes Add methods to the prototype of the existing class All instances of the class will get those methods You can extend built in classes too - with a couple of caveats Generally bad to extend the prototype of Object Generally accepted as bad to extend the prototype of DOM classes, although MooTools and Prototype do this
  • 8. String.prototype.articulize = function() { if(["a", "e", "i", "o", "u"].indexOf(this[0].toLowerCase()) ↳ >= 0) { return "an " + this; } else { return "a " + this; } }; console.log("Pig".articulize()); // logs "a Pig" console.log("Elephant".articulize()); // logs "an Elephant" Animal.prototype.speak = function() { console.log("I'm " + this.name.articulize()); }; animal.speak(); //logs "I'm an animal"
  • 9. Inheritance Create a new constructor function Assign a new instance of the base class to the prototype function A { ... } function B { ... } B.prototype = new A;
  • 10. function Pig() { this.name = "pig"; } Pig.prototype = new Animal; var pig = new Pig(); pig.speak(); // logs "I'm a pig" console.log(pig.toString()); // logs "[pig Animal]" Animal.prototype.countLegs = function() { return this.legs || 0; }; Pig.prototype.legs = 4; console.log(animal.valueOf() + " has " + animal.countLegs() + ↳" legs"); // logs "animal has 0 legs"; console.log(pig.valueOf() + " has " + pig.countLegs() + ↳" legs"); // logs "pig has 4 legs";
  • 11. function Eisbein() { this.legs = 1; // Instance variable } Eisbein.prototype = new Pig; var eisbein = new Eisbein(); eisbein.speak(); // logs "I'm a pig" console.log(eisbein.valueOf() + " has " + ↳eisbein.countLegs() + " legs"); ↳// logs "pig has 1 legs";
  • 12. Calling base class methods Use Function#call to call the base class method in the context of the current class Base.prototype.method.call(this); Call is useful in many other places too Array.prototype.slice.call(arguments); //creates a real array from the arguments oject
  • 13. Pig.prototype.speak = function() { Animal.prototype.speak.call(this); console.log("Snork"); }; pig.speak(); // logs "I'm a pignSnork" Eisbein.prototype.speak = function() { Pig.prototype.speak.call(this); console.log("Sizzle"); }; eisbein.speak(); ↳// logs "I'm a pignSnorknSizzle"
  • 14. Making it Classical Create a Class object to create classes make it look more like classical inheritance have easier access to super class methods
  • 15. (function(global) { var isFn = function(fn) { return typeof fn == "function"; }; global.Class = function() {}; global.Class.create = function(superClass) { var klass = function(magic) { // call init only if there's no magic cookie if(magic != isFn && isFn(this.init)) { this.init.apply(this, arguments); } }; klass.prototype = new this(isFn); for(key in superClass) { (function(fn, superFn) { // create a closure k.prototype[key] = !isFn(fn) || !isFn(superFn) ? fn : function() { this.super = sfn; return fn.apply(this, arguments); }; })(superClass[key], k.prototype[key]); } klass.prototype.constructor = klass; klass.extend = this.extend || this.create; return klass; }; })(this);
  • 16. (function(global) { var isFn = function(fn) { return typeof fn == "function"; }; global.Class = function() {}; global.Class.create = function(derived) { var klass = function(magic) { // call init only if there's no magic cookie if(magic != isFn && isFn(this.init)) { this.init.apply(this, arguments); } };
  • 17. // use our private method as magic cookie klass.prototype = new this(isFn); for(key in derived) { (function(fn, superFn) { // create a closure klass.prototype[key] = !isFn(fn) || !isFn(superFn) ? fn : function() { this.super = superFn; return fn.apply(this, arguments); }; })(derived[key], klass.prototype[key]); } klass.prototype.constructor = klass; klass.extend = this.extend || this.create; return klass; }; })(this);
  • 18. var Animal = Class.create({ init: function() { this.name = "animal"; }, speak: function() { console.log("I'm " + this.name.articulize()); }, toString: function() { return "[" + this.name + " Animal]"; }, valueOf: function() { return this.name; } }); var animal = new Animal(); animal.speak(); // logs "I'm an animal" console.log(animal.toString()); // logs [animal Animal] console.log(animal.valueOf()); // logs animal
  • 19. var Pig = Animal.extend({ init: function() { this.name = "Pig"; }, speak: function() { this.super(); console.log("Snork"); } }); var Eisbein = Pig.extend({ speak: function() { this.super(); console.log("Sizzle"); } }); var pig = new Pig(); pig.speak(); // logs "I'm a pignSnork" var eisbein = new Eisbein(); eisbein.speak(); // logs "I'm a pignSnorknSizzle"

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n