Say I have a classe in JS with prototype functions...
function Foo() {
this.stuff = 7;
this.otherStuff = 5;
}
Foo.prototype.doSomething = function() { };
Foo.prototype.doSomethingElse = function() { };
Now say I want to "extend" this class by subclassing it. In Java this would look like...
public class Bar extends Foo {}
Now I know in JS there really isn't a concept of class, everything can be altered and it all really just boils down to a crap-ton of dictionaries but nonetheless, I should be able to copy the prototype of one class and append it to the prototype of another, right?
What would the code for something like that look like in vanilla JS?
One of the way is like below,
function Foo() {
this.stuff = 7;
this.otherStuff = 5;
}
Foo.prototype.doSomething = function() { alert("some"); };
Foo.prototype.doSomethingElse = function() { };
function Bar() {
Foo.call(this); // this line
}
Bar.prototype = Object.create(Foo.prototype);
var b = new Bar();
b.doSomething();
Something like this...
function Bar(){
// your code
}
Bar.prototype = new Foo(); // Bar extends Foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With