60

What is the right/best way to extend a javascript class so Class B inherits everything from the class A (class B extends A)?

Francis Lewis
  • 8,872
  • 9
  • 55
  • 65
xpepermint
  • 35,055
  • 30
  • 109
  • 163
  • 3
    Actualy... is there some other way but b.prototype = new a; – xpepermint Feb 13 '10 at 00:52
  • 1
    JavaScript doesn't have classes. Therefore, this entire question doesn't make sense. Are you talking about Java? Or ActionScript? Those *do* have classes, but they have absolutely nothing to do with JavaScript. Or are you talking about some JavaScript library which implements class-based OO in JavaScript, like MooTools for example? In that case, the answer depends on what library you are talking about. – Jörg W Mittag Feb 13 '10 at 01:03
  • There is my Class object: https://github.com/reduardo7/sjsClass/blob/master/sjsclass.js – Eduardo Cuomo Sep 13 '13 at 21:01
  • 1
    Take a look at this lightweight library that gives you exactly what you're asking for: Extending classes in javascript. As a bonus, it also adds interfaces and traits/mixins. https://github.com/haroldiedema/joii – Harold Jan 22 '14 at 15:15
  • See short synopsis of Javascript prototype chain, at Mozilla site: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain – J Slick May 20 '14 at 22:08

3 Answers3

57

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

cletus
  • 616,129
  • 168
  • 910
  • 942
30

Douglas Crockford has some very good explanations of inheritance in JavaScript:

  1. prototypal inheritance: the 'natural' way to do things in JavaScript
  2. classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript
Aurovrata
  • 2,000
  • 27
  • 45
Annabelle
  • 10,596
  • 5
  • 27
  • 26
  • 1
    wow, this is so well explained by Douglas Crockford, thanks for these great links. His patterns to create [public/privileged/private](https://crockford.com/javascript/private.html) methods is a revelation. – Aurovrata Aug 13 '18 at 17:47
1
   extend = function(destination, source) {   
          for (var property in source) {
            destination[property] = source[property];
          }
          return destination;
    };

Extending JavaScript

You could also add filters into the for loop.

  • 8
    This is neither what OP asked nor correct "extend" - you should iterate over Object.keys or at least check for hasOwnProperty – Kamil Tomšík Aug 30 '13 at 20:39
  • Needs hasOwnProperty check and will overwrite methods and properties if they are the same, without the ability to call the super class method later. – Rob Evans Apr 07 '14 at 14:35