Javascript extends class [closed]
Asked Answered
O

3

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)?

Outwear answered 13/2, 2010 at 0:50 Comment(5)
Actualy... is there some other way but b.prototype = new a;Outwear
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.Conwell
There is my Class object: github.com/reduardo7/sjsClass/blob/master/sjsclass.jsWhinny
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. github.com/haroldiedema/joiiGladiatorial
See short synopsis of Javascript prototype chain, at Mozilla site: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…Cinthiacintron
S
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.

Superscription answered 13/2, 2010 at 0:57 Comment(2)
Second link is dead.Paphlagonia
The second link is now here: bolinfest.com/javascript/inheritance.phpSporogony
B
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
Benuecongo answered 13/2, 2010 at 1:9 Comment(1)
wow, this is so well explained by Douglas Crockford, thanks for these great links. His patterns to create public/privileged/private methods is a revelation.Fowl
J
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.

Junker answered 28/10, 2012 at 15:28 Comment(2)
This is neither what OP asked nor correct "extend" - you should iterate over Object.keys or at least check for hasOwnPropertySchleicher
Needs hasOwnProperty check and will overwrite methods and properties if they are the same, without the ability to call the super class method later.Dart

© 2022 - 2024 — McMap. All rights reserved.