JavaScript Classes &    Inheritance      Marc Heiligers      @marcheiligers
Basic JS ClassesFunctions act as constructorsFunctions have a prototypeUse new to create an instance of a typeCall instanc...
function Animal() {  this.name = "animal";}Animal.prototype.speak = function() {   console.log("Im a " + this.name);};var ...
ObjectAll JS objects inherit from ObjectObject has 2 standard methods:    toString    valueOfLot’s of non-standard and new...
Overriding MethodsCan override super class methods by:   attaching new methods to the prototype property   eg. Animal.prot...
console.log(animal.toString()); //logs "[object Object]"Animal.prototype.toString = function() {   return "[" + this.name ...
Add methods to existing ClassesAdd methods to the prototype of the existing classAll instances of the class will get those...
String.prototype.articulize = function() {   if(["a", "e", "i", "o", "u"].indexOf(this[0].toLowerCase())    ↳ >= 0) {     ...
InheritanceCreate a new constructor functionAssign a new instance of the base class to the prototype   function A { ... } ...
function Pig() {  this.name = "pig";}Pig.prototype = new Animal;var pig = new Pig();pig.speak(); // logs "Im a pig"console...
function Eisbein() {  this.legs = 1; // Instance variable}Eisbein.prototype = new Pig;var eisbein = new Eisbein();eisbein....
Calling base class methodsUse Function#call to call the base class method in the contextof the current class   Base.protot...
Pig.prototype.speak = function() {   Animal.prototype.speak.call(this);   console.log("Snork");};pig.speak(); // logs "Im ...
Making it ClassicalCreate a Class object to create classes   make it look more like classical inheritance   have easier ac...
(function(global) {  var isFn = function(fn) {     return typeof fn == "function";  };  global.Class = function() {};  glo...
(function(global) {  var isFn = function(fn) {     return typeof fn == "function";  };  global.Class = function() {};  glo...
// use our private method as magic cookie    klass.prototype = new this(isFn);   for(key in derived) {     (function(fn, s...
var Animal = Class.create({  init: function() {     this.name = "animal";  },  speak: function() {     console.log("Im " +...
var Pig = Animal.extend({  init: function() {     this.name = "Pig";  },  speak: function() {     this.super();     consol...
Questions?
Upcoming SlideShare
Loading in...5
×

JavaScript Classes and Inheritance

1,625

Published on

A short introduction into prototypal inheritance in JS followed by a function to make it look like classical inheritance.

Published in: Technology, Business
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,625
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
130
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • JavaScript Classes and Inheritance

    1. 1. JavaScript Classes & Inheritance Marc Heiligers @marcheiligers
    2. 2. Basic JS ClassesFunctions act as constructorsFunctions have a prototypeUse new to create an instance of a typeCall instance methods with dot notation
    3. 3. function Animal() { this.name = "animal";}Animal.prototype.speak = function() { console.log("Im a " + this.name);};var animal = new Animal();animal.speak(); //logs "Im a animal"
    4. 4. ObjectAll JS objects inherit from ObjectObject has 2 standard methods: toString valueOfLot’s of non-standard and newer methods: https://developer.mozilla.org/en/JavaScript/Reference/ Global_Objects/Object
    5. 5. Overriding MethodsCan override super class methods by: attaching new methods to the prototype property eg. Animal.prototype.toString = function() { ... }
    6. 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. 7. Add methods to existing ClassesAdd methods to the prototype of the existing classAll instances of the class will get those methodsYou 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. 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("Im " + this.name.articulize());};animal.speak(); //logs "Im an animal"
    9. 9. InheritanceCreate a new constructor functionAssign a new instance of the base class to the prototype function A { ... } function B { ... } B.prototype = new A;
    10. 10. function Pig() { this.name = "pig";}Pig.prototype = new Animal;var pig = new Pig();pig.speak(); // logs "Im 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. 11. function Eisbein() { this.legs = 1; // Instance variable}Eisbein.prototype = new Pig;var eisbein = new Eisbein();eisbein.speak(); // logs "Im a pig"console.log(eisbein.valueOf() + " has " +↳eisbein.countLegs() + " legs");↳// logs "pig has 1 legs";
    12. 12. Calling base class methodsUse Function#call to call the base class method in the contextof 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. 13. Pig.prototype.speak = function() { Animal.prototype.speak.call(this); console.log("Snork");};pig.speak(); // logs "Im a pignSnork"Eisbein.prototype.speak = function() { Pig.prototype.speak.call(this); console.log("Sizzle");};eisbein.speak();↳// logs "Im a pignSnorknSizzle"
    14. 14. Making it ClassicalCreate a Class object to create classes make it look more like classical inheritance have easier access to super class methods
    15. 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 theres 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. 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 theres no magic cookie if(magic != isFn && isFn(this.init)) { this.init.apply(this, arguments); } };
    17. 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. 18. var Animal = Class.create({ init: function() { this.name = "animal"; }, speak: function() { console.log("Im " + this.name.articulize()); }, toString: function() { return "[" + this.name + " Animal]"; }, valueOf: function() { return this.name; }});var animal = new Animal();animal.speak(); // logs "Im an animal"console.log(animal.toString()); // logs [animal Animal]console.log(animal.valueOf()); // logs animal
    19. 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 "Im a pignSnork"var eisbein = new Eisbein();eisbein.speak(); // logs "Im a pignSnorknSizzle"
    20. 20. Questions?
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×