What is the right/best way to extend a javascript class so Class B inherits everything from the class A (class B extends A)?
Asked
Active
Viewed 1.1e+01k times
60
-
3Actualy... is there some other way but b.prototype = new a; – xpepermint Feb 13 '10 at 00:52
-
1JavaScript 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
-
1Take 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 Answers
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
-
7
-
3The second link is now here: http://bolinfest.com/javascript/inheritance.php – Ed Gibbs Aug 02 '15 at 06:02
30
Douglas Crockford has some very good explanations of inheritance in JavaScript:
- prototypal inheritance: the 'natural' way to do things in JavaScript
- classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript
-
1wow, 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;
};
You could also add filters into the for loop.
-
8This 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