Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Inheritance in Javascript

I am wondering how to simulate Class Inheritance in JavaScript. I know class doesn't apply to JavaScript, the way we use is Functions to create objects and do the inheritance things through Prototype object.

For example, how do you convert this structure into JavaScript :

public class Mankind {
    public string name;
    public string lastname;
}

public class Person: Mankind {
    public void Run(string fromWhat) {
        //write the run logic
    }
}

What is the equivalent of this piece of code in JavaScript.

Edit:

I've also found another link where Douglas Crockford explains different inheritance models as CMS does: Classical Inheritance in JavaScript.

Hope it helps others as well.

like image 518
Tarik Avatar asked Jan 25 '10 01:01

Tarik


2 Answers

There are plenty ways of implementing inheritance and behavior reuse in JavaScript, perhaps the way that is more similar to your class-based OOP example would be the pseudo-classical inheritance:

function Mankind (name, lastname) {
  this.name = name;
  this.lastname = lastname;
}

function Person (name, lastname) {
  this.name = name;
  this.lastname = lastname;

  this.run = function() {
    // run logic
  };
}
Person.prototype = new Mankind();
Person.prototype.walk = function () {
  // walk logic
};

The difference between run and walk is that the first will exist on every object instance of Person, and the second method, walk, will exist only in Person.prototype and will be accessed through the prototype chain.

In this pattern you see a bit of code duplication, we need the logic to initialize the fields also on the inherited constructor, another pattern that avoids this, is Constructor Function application:

function Mankind (name, lastname) {
  this.name = name;
  this.lastname = lastname;
}

function Person (name, lastname) {
  Mankind.apply(this, arguments);
  this.run = function() {
    // run logic
  };
}

More info:

  • How to inherit from a class in JavaScript (various examples)
  • Inheritance Patterns in JavaScript (article)
  • Classical Inheritance in JavaScript (article)
like image 63
Christian C. Salvadó Avatar answered Sep 18 '22 02:09

Christian C. Salvadó


Updated for ES 6:

class Mankind {
    constructor (lastName, firstName) {
      this.lastName = lastName;
      this.firstName = firstName;
    }
}

class Person extends Mankind {
    run (fromWhat) {
        //write the run logic
    }
}
like image 30
Jared Smith Avatar answered Sep 22 '22 02:09

Jared Smith