[英]Multiple inheritance in javascript
这是关于oop in js的一些问题(以下代码中的问题)。
<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>
C.prototype = new A();
C.prototype = new B();
javascript不支持多重继承。 您要做的就是让C从B继承而来,而不是A继承。
你不能 当你这样做
C.prototype = new A();
C.prototype = new B();
您只是在更改prototype
指向的对象。 因此,C曾经从A继承,但是现在它从B继承了。
您可以伪造多重继承
C.prototype = new A();
for (var i in B.prototype)
if (B.prototype.hasOwnProperty(i))
C.prototype[i] = B.prototype[i];
现在您将拥有A和B的属性/方法,但实际上并没有继承,因为对B prototype
对象的任何更改都不会传播到C。
您需要使用var
语句声明变量a
,以使其在函数中处于本地状态。
function A(){
var a = 'a - private FROM A()';
this.a = 'a - public FROM A()';
this.get_a = function(){
return a;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.