Wednesday, 13 May 2015

Inheritance in Javascript

in Javascript inheritance can be achieved by using below two methods
1.Prototype chaining
2.Constructor stealing

1.prototype chaining

base=function()
{
this.name="base";
}

derived=function
{
this.marks="20";

this.prototype=new base();//creating inheritance using prototype
}

with above approach we face some problems while usig collectios like arrays.

Example


base=function()

{
this.name="base";
this.languages=["tel","eng","hindi"];
}

derived=function
{
this.marks="20";

this.prototype=new base();//creating inheritance using prototype
}

var  d1=new derived();
var d2=new derived();
d1.push("Kannada");

alert(d1.laguages) //prints tel,eng,hindi,kannada

alert(d2.languages) //also prints tel,eng,hindi,kannada

this is the problem with prototype chaiing when we use arrays, and try tomodify them,it will be reflected in all instances of the class.as when we modify an array, it points to a different location/reference


Constructor stealing


This is the second way of implementing inheritance in javascript where we invoke constructor of the parent class directly in the child class to perform inheritance.


base=function()
{
this.name="base";
}

derived=function
{
this.marks="20";

this.prototype=new base();//creating inheritance using prototype
}

with above approach we face some problems while usig collectios like arrays.

Example


base=function()

{
this.name="base";
this.languages=["tel","eng","hindi"];
}

derived=function
{
this.marks="20";

base.call(this);
}

var  d1=new derived();
var d2=new derived();
d1.push("Kannada");

alert(d1.laguages) //prints tel,eng,hindi,kannada

alert(d2.languages) // prints tel,eng,hindi 

so to avoid problems usig prototype chaiing, we can prefer constructor stealing.



1 comment:

  1. No deposit bonus codes 2020 - DrmCD
    There are a 서산 출장마사지 few welcome bonuses available to new and existing players at casinos. Find 안성 출장샵 out 구미 출장안마 about no deposit 화성 출장안마 bonus codes 2020 and grab 남양주 출장샵 the best bonuses.Dec 9, 2020

    ReplyDelete

Search This Blog