0

Here's some question about oop in js (questions in the code below).

<html>
    <script>
    function A(){
      a = 'a - private FROM A()';
      this.a = 'a - public FROM A()';
      this.get_a = function(){
        return a;
      }
    }

    function B(){
      this.b = 'b - private FROM B()';
      this.a = 'a - public FROM B() ';
    }

    C.prototype = new A();
    C.prototype = new B();
    C.prototype.constructor = C;
    function C() {
      A.call(this);
      B.call(this);
    }

    var c = new C();

    //I've read paper about oop in Javacscript but they never talk 
    //(the ones have read of course) about multiple inheritance, any 
    //links to such a paper?

    alert(c.a);
    alert(c.b);
    alert(c.get_a());

    //but

    //Why the hell is variable a from A() now in the Global object?
    //Look like C.prototype = new A(); is causing it.

    alert(a);

    </script>
</html>
2
  • I guess I should clarify my question : What are the drawback of multi-inheritance in js? And why variable a is in global scope? Commented Sep 22, 2010 at 15:10
  • 2
    Then put that in the question - use the edit button Commented Sep 22, 2010 at 15:14

3 Answers 3

7
C.prototype = new A();
C.prototype = new B();

Multiple inheritence isn't supported in javascript. All you've done is make C inherit from B instead of A.

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

Comments

6

You can't. When you do this

C.prototype = new A();
C.prototype = new B();

You are merely changing the object that prototype points to. So C used to inherit from A, but now it inherits from B.

You can fake multiple inheritance

C.prototype = new A();

for (var i in B.prototype)
  if (B.prototype.hasOwnProperty(i))
    C.prototype[i] = B.prototype[i];

Now you'd have the properties/methods from both A and B, but you don't really have inheritance, since any changes to the prototype object of B will not propagate to C.

Comments

3

You need to declare the variable a with the var statement in order to make it local to the function.

function A(){
  var a = 'a - private FROM A()';
  this.a = 'a - public FROM A()';
  this.get_a = function(){
    return a;
  };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.