Thursday, June 11, 2015

inheritance in JavaScript

inheritance in JavaScript


In the JavaScript, we can implement the inheritance using the some alternative ways and we cannot define a class keyword but we create a constructor function and using new keyword achieve it.  

The some alternative ways as given  below.
  1. Pseudo classical inheritance
  2. Prototype inheritance
Pseudo classical inheritance is the most popular way. In this way, create a constructor function using the new operator and add the members function with the help for constructor function prototype.

The prototype based programming is a technique of object oriented programming. In this mechanism we can reuse the exiting objects as prototypes. The prototype inheritance also know as prototypal, 
classless or instance based inheritances.

The Inheritance example for prototype based as given below

  // Create a helper function.
    if (typeof Object.create !== 'function') {

        Object.create = function (obj) {
            function fun() { };
            fun.prototype = obj;
            return new fun();
        };
    }

    //This is a parent class.
    var parent = {
        sayHi: function () {
            alert('Hi, I am parent!');
        },
        sayHiToWalk: function () {
            alert('Hi, I am parent! and going to walk!');
        }
    };

    //This is child class and the parent class is inherited in the child class.
    var child = Object.create(parent);

    child.sayHi = function () {
        alert('Hi, I am a child!');
    };

<button type="submit" onclick="child.sayHi()"> click to oops</button>

The output is : Hi, I am a child!

No comments:

Post a Comment