Javascript foundations: Inheritance

3,296 views

Published on

This presentation forms part of a tutorial on learning Javascript foundations. It introduces the concept of classes and inheritance in object oriented programming. Classical and prototypal inheritance in Javascript are discussed and the Object.beget method is introduced.

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,296
On SlideShare
0
From Embeds
0
Number of Embeds
322
Actions
Shares
0
Downloads
0
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Javascript foundations: Inheritance

  1. 1. inheritance Learning Javascript foundations John Hunter 12 November 2008
  2. 2. are these the same thing?
  3. 3. 1 2 radio toggleButton we have one radio with two buttons
  4. 4. toggleButton toggleUp () toggleDown () toggleButtons share the same behaviour (methods) we could say they are a particular class of objects
  5. 5. Class Defines the abstract characteristics of a thing (object), including the thing's characteristics (its attributes, fields or properties) and the thing's behaviours (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur colour (characteristics), and the ability to bark and sit (behaviours). source: wikipedia/Object_orientated_programming
  6. 6. Javascript does not have formal classes it can approximate class based programming but it has other mechanisms for inheritance
  7. 7. class-based inheritance vs. prototype-based inheritance nothing to do with the Prototype framework
  8. 8. Classical inheritance ToggleButton instantiate tuningButton volumeButton function ToggleButton () { … } var tuningButton = new ToggleButton(); var volumeButton = new ToggleButton();
  9. 9. Prototypal inheritance toggleButton prototype tuningButton volumeButton beget var toggleButton = { … }; var tuningButton = Object.beget(toggleButton); var volumeButton = Object.beget(toggleButton);
  10. 10. toggleButton toggleUp () toggleDown () prototype Then look here tuningButton First look here tuningButton.toggleUp();
  11. 11. class-based approach: you always have to create a class blueprint in order to create an object prototype-based approach: you can use an existing object as a prototype for more objects
  12. 12. Object.beget = function (obj) { var F = function () {}; F.prototype = obj; return new F(); }; // myThing = Object.beget(thing); the beget method returns an object that uses the argument as its prototype source: Doug Crockford
  13. 13. There is more to inheritance ...but that’s all for now!
  14. 14. Review classes of objects share characteristics and behaviour Javascript supports several inheritance mechanisms Class-based (but not true classes) Prototype-based
  15. 15. Thanks

×