3

I have a situation here. I have two modules(nothing but javascript function) defined like this:

Module1:

define(function(){
    function A() {
        var that = this;
        that.data = 1
        // ..
    }
    return A; 
});

Module2:

define(function(){   
    function B() {
        var that = this;
        that.data = 1;
        // ...
    }
    return B; 
});

How to inhert both modules inside other module?

Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168
Rahul Pal
  • 96
  • 7
  • 4
    Javascript doesn't have inheritance, it uses prototypes. – Antimony May 18 '13 at 19:39
  • Questions about multiple inheritance in JavaScript [have been asked on Stack Overflow many times before](https://www.google.com/#output=search&sclient=psy-ab&q=site:stackoverflow.com+multiple+inheritance+javascript&oq=site:stackoverflow.com+multiple+inheritance+javascript&gs_l=hp.3...926.20236.1.20465.80.74.3.3.3.0.169.4177.71j3.74.0...0.0...1c.1.14.hp.VBc-U-g0D_M&psj=1&bav=on.2,or.r_cp.r_qf.&bvm=bv.46751780,d.dmg&fp=e16b3377a0a5d434&biw=1366&bih=639). You might be able to find a solution from one of these duplicate questions. – Anderson Green May 18 '13 at 19:39
  • @Anderson Care to link to a duplicate? – deceze May 18 '13 at 19:42
  • 1
    @deceze This looks like a very close match: http://stackoverflow.com/questions/6887828/does-javascript-support-multiple-inheritance-like-c – Anderson Green May 18 '13 at 19:43
  • those links are good too :) – Dory Zidon May 18 '13 at 19:48
  • 2
    @Antimony - it has prototype-based inheritance rather than class-based inheritance. It's still inheritance... – Mark Reed May 18 '13 at 19:50

2 Answers2

4

1) In js everything is just an object.

2) Javascript inheritance uses prototype inheritance and not classic inheritance.

JavaScript doesn't support multiple inheritance. To have both of them inside the same class try to use mixins that are better anyhow:

function extend(destination, source) {
  for (var k in source) {
    if (source.hasOwnProperty(k)) {
      destination[k] = source[k];
    }
 }
 return destination; 
 }

 var C = Object.create(null);
 extend(C.prototype,A);
 extend(C.prototype,B);

mixins:

http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/

inheritance in js:

http://howtonode.org/prototypical-inheritance

http://killdream.github.io/blog/2011/10/understanding-javascript-oop/index.html

Dory Zidon
  • 10,497
  • 2
  • 25
  • 39
0

Here you go a little demonstration of the functionality you want to achieve:

var obj1 = function() {
  var privateMember = "anything";
  this.item1 = 1;
}

var obj2 = function() {
  this.item2 = 2;
}

var objInheritsBoth = function() {
  obj1.call(this); // call obj1 in this context
  obj2.call(this);
  this.item3 = 3;
}

var x = new objInheritsBoth();

console.log(x.item1, x.item2, x.item3); // 1 2 3
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169