0

Suppose in JavaScript, I have a class Human and another class Child(Please dont kill me for using the word class)

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

function Child(age){
    this.age=age;
}

I can create an object of Human as:

var h=new Human('MyName')

and an object of child as:

var c=new Child(10)

I can also do inheritance by:

var ih=Object.create(h)

to inherit/copy the created object h.

But, is there any way I can create an object of Child and let it inherit the Human class as well. i.e, my object should have both Human and Child attributes. And as far as Javascript is concerned, I believe it sounds like multiple inheritance. Is there a way to achieve this?

Mkl Rjv
  • 6,815
  • 5
  • 29
  • 47
  • You mean, `Child` has to inherit `Human`? – thefourtheye Apr 16 '14 at 08:06
  • 1
    I'd recommend to read the following article for better understanding how inheritance in JavaScript work: https://alexsexton.com/blog/2013/04/understanding-javascript-inheritance/. – VisioN Apr 16 '14 at 08:08
  • 1
    JavaScript is "Single Inheritance" insofar are there is only one [prototype] object looked up per level of resolving properties. As such, MI can only be emulated in JavaScript (such as "copying properties", much like Traits are emulated in Scala) without entirely re-creating the dispatch mechanism. – user2864740 Apr 16 '14 at 08:10

2 Answers2

0

There can be only one prototype, but you can make mixed objects like in the code below:

function Human(name){ ... }

function NoiseSource(decibel){ ... }

function Child(age){ ... }

var dave = new Child(3);
$.extend(dave, new Human("Dave"));
$.extend(dave, new NoiseSource(120));

But in you example you dont need it, since you need single Human parent class for Child, which can be achieved via regular prototypal inheritance.

setec
  • 15,506
  • 3
  • 36
  • 51
0

Previous stackoverflow question: Good Example of JavaScript's Prototype-Based Inheritance.

Nice Java/javascript side-by-side code comparison here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model

I suggest (in your case to use this.base) :

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

    function Child(age){
        this.base = Human;
        this.age=age;
    }

var myChild = new Child(5) // 5 yr old
myChild.name = 'Harry';
console.log( myChild );

that in the firefox Console gives:

Child { age=5, name="Harry", base=Human()}

hope that helps

Community
  • 1
  • 1
GavinBrelstaff
  • 3,016
  • 2
  • 21
  • 39