Wednesday 18 June 2014

Inheritance in oopJs

//PARENT class

    function Parent()
    {
        var name =  "devesh"; //private variables
        this.pass = "123"; //public variables
        _protected = "protected";
        pro = "new proc";
       
        // private methods are declared within the scope of constructor   
        var privateMethod = function(){
        //var self =this
        // self.walk(); //accessing public methods in private method
        return console.log(name);
        }
        // privileged methods are methods that are public and same time have access to privated properties/methods   
        this.privilegedMethod = function(){
        return privateMethod();
        }

    }
    Parent.fixed = 3;
    // public methods   
    Parent.prototype.walk = function(){
    console.log("i am walking via public method");
    }

    Parent.prototype.sayHello = function(){
    console.log("say hello from parent");
    }

    //define child class
    function Child(){
    Parent.call(this) //call constructor of parent class
    }
    //var parentObj = new Parent({name:"devesh",pass: "1234", protect:"protected varibale"});
    Child.prototype = new Parent();  //Inherit parent class

    Child.prototype.constructor = Child // Correct constrcutor pointer as it was pointing to parent class

    Child.prototype.sayHello = function(){
    console.log("say hello from child");
    Parent.prototype.sayHello.call(this);
    console.log(self._protected);
    console.log(self.pro);
    console.log(self.name);
   
    //Parent.prototype.sayHello.call(this); way to call parent call method in child class....
    }

    Child.prototype.sayGoodBye = function(){
    console.log("good bye");
    }


    var childObj = new Child();   // Child.prototype = Object.create(Parent.protoype);

    childObj.sayHello();
    childObj.privilegedMethod();
    childObj.walk();
    console.log(childObj.fixed);
   

function Person(){
  if(Person.count == undefined){
    Person.count = 1;
  }
  else{
    Person.count ++;
  }
  console.log(Person.count);
}

var p1 = new Person();
var p2 = new Person();
var p3 = new Person();



//. In object oriented programing polymorphism is used to call the same method on different objects to have them respond in their own way.
function mainfuncone()
{
this.prop_1 =27;

}

mainfuncone.prototype.polyfuncname=function()
{
this.prop_1 += 10;
}

function mainfunctwo()
{
this.prop_11 =30;

}

mainfunctwo.prototype.polyfuncname=function()
{
this.prop_11 +=10;

}

obj1=new mainfuncone;
obj2=new mainfunctwo;

//call functions
obj1.polyfuncname();
obj2.polyfuncname();

//access properties values by using polymorphism
alert(obj1.prop_1);
alert(obj2.prop_11)

No comments:

Post a Comment