Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Implement "extends" like functionality (REALLY simple inheritance)

Tags:

javascript

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?

like image 275
Cody Smith Avatar asked Jul 17 '13 05:07

Cody Smith


2 Answers

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(); 
like image 190
Vinay Avatar answered Sep 22 '22 18:09

Vinay


Something like this...

function Bar(){
    // your code
}

Bar.prototype = new Foo(); // Bar extends Foo
like image 28
mohkhan Avatar answered Sep 22 '22 18:09

mohkhan