Performing inheritance in JavaScript

RC1140 picture RC1140 · Oct 19, 2009 · Viewed 13.5k times · Source

Now while I know that you can not perform inheritance like you would in C#, I have seen it mentioned on the Internet that it is kind of possible. If it's not possible using plain JavaScript code then would it be possible using Ext JS and if so how?

Answer

Christian C. Salvadó picture Christian C. Salvadó · Oct 19, 2009

The JavaScript object oriented paradigm is prototype based. There are no "classes", just objects.

You can implement inheritance in different ways. The two more popular alternatives are the "pseudo-classical" and the "prototypal" forms. For example:

Pseudo-classical inheritance

I think this is the most popular way. You create constructor functions that you use with the new operator, and you add members through the constructor function prototype.

// Define the Person constructor function
function Person() {}

Person.prototype.sayHello = function(){
    alert ('hello');
};

// Define the Student constructor function
function Student() {}

// Inherit from Person
Student.prototype = new Person();

// Correct the constructor pointer, because it points to Person
Student.prototype.constructor = Student;

// Replace the sayHello method (a polymorphism example)
Student.prototype.sayHello = function () {
    alert('hi, I am a student');
}

var student1 = new Student();
student1.sayHello();

Prototypal inheritance

Basically we make a helper function that takes an object as a parameter and returns an empty new object that inherits from the old one, objects inherit from objects.

// Helper function
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

var person = {
    sayHello : function () {
        alert('Person object');
    },
    walk : function () {
        alert('walk');
    }
};

var student1 = Object.create(person);
student1.sayHello = function () {
    alert('hello I am a student');
};

Another interesting form is the parasitic inheritance. In the "derived" constructor you create a "base" object instance. That object is augmented and that new instance is returned:

// Person constructor function
function Person(name) {
    this.name = name;
}

function Student(value) {
    var that = new Person(value);
    that.sayHello = function () {
        alert('hello I am a student');
    };
    return that;
}