[ACCEPTED]-Performing inheritance in JavaScript-prototypal-inheritance

Accepted answer
Score: 49

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

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

Pseudo-classical inheritance

I 11 think this is the most popular way. You 10 create constructor functions that you use with the new operator, and 9 you add members through the constructor 8 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 7 function that takes an object as a parameter 6 and returns an empty new object that inherits 5 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 4 is the parasitic inheritance. In the "derived" constructor 3 you create a "base" object instance. That 2 object is augmented and that new instance 1 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;
}
Score: 3

JavaScript inheritance is done through prototypes. You 11 do not define anything with a class keyword, but 10 you make a function that's used as a constructor 9 to build new objects (with the new keyword 8 ).

function person(name) {
    this.name = name;
}

person.prototype.getName = function() {
    return this.name;
}

var john = new person('john');
alert( john.getName() );

You can access this prototypal method 7 with:

person.prototype.getName

All newly created objects are constructed 6 based on the core constructors (sometimes 5 called classes by people coming from classical 4 inheritance languages, or the core objects) such 3 as Object, so every object in JavaScript has access 2 to Object.prototype. If you were to make a custom method 1 for all objects you would do:

Object.prototype.foo = function(){};
alert( typeof ({}).foo ) // 'function'

Key notes:

  • The this word is used to refer to the current object, so this.name sets the name property of the object being created when new person is invoked.
  • You can define new prototypal methods on the constructor with constructorName.prototype.nameOfMethod = function(){} after you define the constructor. You do not need to define it inside of the constructor, and it's more efficient this way.
  • Unless you explicitly define properties on the object, so with the john object I made, since there is no getName method directly attached to the john object, the interpreter needs to travel up to the prototype of the john object, which is the person.prototype and access the method from there. You can use hasOwnProperty to see if an object directly owns a property or not.

Reference:

Score: 3

If you have done Object Oriented Programming 64 in JavaScript, you will know that you can 63 create a class as follows:

Person = function(id, name, age){
    this.id = id;
    this.name = name;
    this.age = age;
    alert('A new person has been accepted');
}

So far our class 62 person only has two properties and we are 61 going to give it some methods. A clean way 60 of doing this is to use its 'prototype' object. Starting 59 from JavaScript 1.1, the prototype object 58 was introduced in JavaScript. This is a 57 built in object that simplifies the process 56 of adding custom properties and methods 55 to all instances of an object. Let's add 54 2 methods to our class using its 'prototype' object 53 as follows:

Person.prototype = {
    /** wake person up */
    wake_up: function() {
        alert('I am awake');
    },

    /** retrieve person's age */
    get_age: function() {
        return this.age;
    }
}

Now we have defined our class 52 Person. What if we wanted to define another 51 class called Manager which inherits some 50 properties from Person. There is no point 49 redefining all this properties again when 48 we define our Manager class, we can just 47 set it to inherit from the class Person. JavaScript 46 doesn't have built in inheritance but we 45 can use a technique to implement inheritance 44 as follows:

Inheritance_Manager = {};//We create an inheritance manager 43 class (the name is arbitrary)

Now let's give 42 our inheritance class a method called extend 41 which takes the baseClass and subClassas 40 arguments. Within the extend method, we 39 will create an inner class called inheritance 38 function inheritance() { }. The reason why 37 we are using this inner class is to avoid 36 confusion between the baseClass and subClass 35 prototypes. Next we make the prototype of 34 our inheritance class point to the baseClass 33 prototype as with the following code: inheritance.prototype 32 = baseClass. prototype; Then we copy the 31 inheritance prototype into the subClass 30 prototype as follows: subClass.prototype 29 = new inheritance(); The next thing is to 28 specify the constructor for our subClass 27 as follows: subClass.prototype.constructor 26 = subClass; Once finished with our subClass 25 prototyping, we can specify the next two 24 lines of code to set some base class pointers.

subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;

Here 23 is the full code for our extend function:

Inheritance_Manager.extend = function(subClass, baseClass) {
    function inheritance() { }
    inheritance.prototype = baseClass.prototype;
    subClass.prototype = new inheritance();
    subClass.prototype.constructor = subClass;
    subClass.baseConstructor = baseClass;
    subClass.superClass = baseClass.prototype;
}

Now 22 that we have implemented our inheritance, we 21 can start using it to extend our classes. In 20 this case we are going to extend our Person 19 class into a Manager class as follows:

We 18 define the Manager class

Manager = function(id, name, age, salary) {
    Person.baseConstructor.call(this, id, name, age);
    this.salary = salary;
    alert('A manager has been registered.');
}

we make it inherit 17 form Person

Inheritance_Manager.extend(Manager, Person);

If you noticed, we have just 16 called the extend method of our Inheritance_Manager 15 class and passed the subClass Manager in 14 our case and then the baseClass Person. Note 13 that the order is very important here. If 12 you swap them, the inheritance will not 11 work as you intended if at all. Also note 10 that you will need to specify this inheritance 9 before you can actually define our subClass. Now 8 let us define our subClass:

We can add more 7 methods as the one below. Our Manager class 6 will always have the methods and properties 5 defined in the Person class because it inherits 4 from it.

Manager.prototype.lead = function(){
   alert('I am a good leader');
}

Now to test it let us create two 3 objects, one from the class Person and one 2 from the inherited class Manager:

var p = new Person(1, 'Joe Tester', 26);
var pm = new Manager(1, 'Joe Tester', 26, '20.000');

Feel free 1 to get full code and more comments at: http://www.cyberminds.co.uk/blog/articles/how-to-implement-javascript-inheritance.aspx

Score: 0

JavaScript is a prototype based inheritance. However if 19 you use Ext-js, it will allow you to have 18 syntax more a classical inheritance syntax. Be 17 warned it is still prototyping under the 16 hood, so there will be some nuances that 15 you should be aware of. Mainly that it is 14 load and go, so the order you load your 13 script matters and your class definitions 12 sit essentially in memory.

There are some 11 good tutorials out there. I suggest going through 10 the initial docs and watching this video. Ext 9 does a pretty good job about making JavaScript 8 feel more like Java or C#, and reducing 7 the amount of markup you write. However 6 the trade off is that you have a higher 5 learning curve for customizing components. Once 4 you get a stronger grasp of the scoping 3 of the language, you will be able to use 2 mixins, functions better to reduce the need 1 for inheritance.

Score: 0

You may try

subClass.prototype.__proto__ = baseClass.prototype;

For details please visit my website.

0

Score: 0

Here is a simple example of inheritance. ClassA 5 is a parent and ClassB is a child and common 4 task is call a print method of ClassA through 3 ClassB, therefore here the first initialized 2 constructor then create prototype method 1 for the parent class.

var ClassA = function() {
this.name = "class A";
 }
var a = new ClassA();
ClassA.prototype.print = function() {
alert(this.name);
}

var inheritsFrom = function (child, parent) {
 child.prototype = Object.create(parent.prototype);
 };
var ClassB = function() {
     this.name = "class B";
     this.surname = "I'm the child";
 }

 inheritsFrom(ClassB, ClassA);
 var b = new ClassB();
 b.print();

More Related questions