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?

6
  • 4
    Javascript doesn't have inheritance, it uses prototypes. Commented May 18, 2013 at 19:39
  • Questions about multiple inheritance in JavaScript have been asked on Stack Overflow many times before. You might be able to find a solution from one of these duplicate questions. Commented May 18, 2013 at 19:39
  • @Anderson Care to link to a duplicate? Commented May 18, 2013 at 19:42
  • 1
    @deceze This looks like a very close match: stackoverflow.com/questions/6887828/… Commented May 18, 2013 at 19:43
  • 2
    @Antimony - it has prototype-based inheritance rather than class-based inheritance. It's still inheritance... Commented May 18, 2013 at 19:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

So... is multiple prototypical inheritance possible...?
use mixins, it's the closest there is. Js doesn't enforce structure or base class methods or properties..in js everything is just an object..
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.