What is the right/best way to extend a javascript class so Class B inherits everything from the class A (class B extends A)?
Javascript extends class [closed]
Asked Answered
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.js –
Whinny
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/joii –
Gladiatorial
See short synopsis of Javascript prototype chain, at Mozilla site: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… –
Cinthiacintron
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.
Second link is dead. –
Paphlagonia
The second link is now here: bolinfest.com/javascript/inheritance.php –
Sporogony
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
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
extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
You could also add filters into the for loop.
This is neither what OP asked nor correct "extend" - you should iterate over Object.keys or at least check for hasOwnProperty –
Schleicher
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.