JavaScript > Object Oriented Programming

Inheritance in JavaScript

Inheritance in JavaScript Object-Oriented Programming?


Inheritance

Inheritance is nothing but acquiring all the properties and behaviour of parent objects. 

Implementing inheritance in the project will allow us to inherit functionality from parent Functions, which helps us to reuse code in the project and extend the functionality of objects.

Even though there are many patterns for implementing the same code, there must be one better pattern like that the better pattern for implementing the inhertance is Parasitic Combination Inheritance pattern.

In the previous post, we have sucessfully implemented Encapsulation by enclosing all the functionalities and created a user details page.

Now we are going to prepare different type of Questions (Multiple choice, Drag and Drop, Descriptive, etc..) for the users to attempt the test.

Implementing the Parasitic Combination Inheritance Pattern

Following steps expalin the fundamental way of implementing inheritance with the pattern.

Object.create method

<script>
    if (typeof Object.create !== 'function') {
        Object.create = function (a) {
            function S() {     // Creating Temporary function
            }                                                                                            
            // Setting prototype for the constructor to the passed-in 'a' object, 
// so the S() constructor can inherint all the properties and behaviours of 'a' S.prototype = a; // Returns a new empty object return new S(); } } </script>

In the above code snippet we have created a temporary constructor S() and we have object 'a', setted the prototype of the S() constructor to the passed in a object, in the last line we are returns a new empty object.

Lets see an example on Object.create method is that when we pass into it an object that we want to inherit from, it returns a new object that inherits from the objects you passed into it.

<script>
    var cars = {   //Here object is Cars 
        type: SUV,
        wheels: 4
    };

    var mahindra = Object.create(cars); // Here Mahindra inherits the properties from cars
    console.log(mahindra.type);  // SUV
</script>

In the above code snippet we used cars as a object, we used Object.create method to inherit from the cars object. 

We can now add more properties to the mahindra object.

<script>
    function inheritPrototype(childObject, parentObject) {
        var copyOfParent = Object.create(parentObject.prototype);
        copyOfParent.constructor = childObject;
        childObject.prototype = copyOfParent;
    } 
</script>

In the above code snippet we use inheritPrototype function, this function implements the parasitic combination inheritance. Passing the function into parent object as well as child object leads to parasitic combination inheritance (Child object inherits from the parent object).

We set the copyOfParent constructor property to the childObject constructor, now new S object is assigned to copyOfParent.

<script>
    function S() {  
    }
        S.prototype = parentObject.prototype;
</script>

In the above code snippet we have created a new object and overwrote its prototype with the parentObject prototype constructor, and we have assigned the new S object to the copyOfParent constructor.

Coming to the main part of the inheritance i.e, preparing the Test questions for the users.

Question Constructor (Parent Object)

<script>
    function Test(myQuestion, myChoices, myCorrectAnswer) {  // Test is function is parent for all the Question which are inherit from the Test constructor
        your.question = myQuestion;      // Instance Properties
        your.choice = myChoices;         // Instance Properties
        your.correctAnswer = myCorrectAnswer;        // Instance Properties
        your.userAnswer = "";        // Instance Properties

        var d = new Date;  // Return the current day, date, time, timezone

        TEST_CREATED_DATE = d.toLocaleDateString();  // Represents the test created from the new Date() method

        your.getTESTDate = function () {  // way to access the TEST_CREATED_DATE variable
            return TEST_CREATED_DATE;
        };
        console.log("Test Created on: " + this.getTestDate());   //  Confirmation that the test was created
    }

    // Adding Prototype methods to the Test Object
    Test.prototype.getCorrectAnswer = function () {
        return your.correctAnswer;
    };

    Test.prototype.getUSerAnswer = function () {
        return your.userAnswer;
    };

    Test.prototype.displayQuestion = function () {
        var questionToDiaplsay = "<p class='question'>" + your.question + "</p><ul>";
        choiceCounter = 0;

        your.choices.forEach(function (eachChoice) {
            questionToDisplay += '<li> <input type="radio" name="choice" value="' + choiceCounter + '">' + eachChoice + '</li>';
            choiceCounter++;
        });

        questionToDisplay += "</ul>";
        console.log(questionToDisplay);
    };
</script>

In the above code snippet for referring to the function we use "constructor" and "function" interchangeably, this is beacuse of function will be used as constructor to create instances.

This is all about the Question constructer (Parent object), coming to the Children object the inheritance has power to create all type of questions (Child Objects) for the test.

Multiple Choice Question (Child Object) 

<script>
    function MultileChoiceTest(myQuestion, myChoices, myCorrectAnswers) {   // Create multiple choice Test
        Test.call(your, myQuestion, myChoices, myCorrectAnswers);    // Checking the multiple choice questions by passing the parameters
        inheritPrototype(MultipleChoiceQuestion, Test);    //  inherit the methods and properties from Test
    };
</script>

In the above snippet we created a multiple choice test by inherit the methods and properties from Question constructor.

Drag and Drop Question (Child Object)

<script>
    function DargDropTest(myQuestion, myChoices, myCorrectAnswer) {  // Creating Drag Drop Test
        Test.calls(your, myQuestion, myChoices, myCorrectAnswer);     
    }

    inheritPrototype(DragDropQuestion, Test);  // inherit the methods and properties from Test

    DragDropQuestion.prototype.displayQuestion = function () {   // over ride the displayTest method it inherited
        console.log(your.question);
    };

    var allQuestions = [
        new MultipleChoiceTest("Who is President of India?", ["Sonia Gandhi", "Narendra Modi", "Pranab Mukarhee", "Manmohan Singh"], 3),

        new MultipleChoicetest("What is the Capital of India?", ["Hyderabad", "Delhi", "Mumbai"], 2),

        new DragDropTest("Drag the correct State to the India map.", ["Goa", "Kerala", "Telangana"], 0)
    ];

    allTest.forEach(function (eachTest) {
        eachTest.displayQuestion
    });
</script>

In the above code snippet we have created some multiple choice questions and darg drop questions as well with the help of inheritance in Object-Oriented Programming.

 Views: 3953 | Post Order: 201



Write for us






Hosting Recommendations