Reputation: 795
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>
Upvotes: 0
Views: 2408
Reputation: 113866
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.
Upvotes: 7
Reputation: 48240
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.
Upvotes: 6
Reputation: 946
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;
};
}
Upvotes: 3