use*_*946 5 javascript inheritance
任何人都可以请帮助以下代码.我试图理解多重继承不确定为什么它不起作用.BTW如果是多重继承的代码.谢谢
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Test Doc</title>
<script type="text/javascript">
function classX(){
this.messageX="this is X Message";
this.alertX=function(){
alert(this.messageX);
};
}
function classY(){
this.messageY="this is Y Message";
this.alertY=function(){
alert(this.messageY);
};
}
function classZ(){
classX.apply(this);
classY.apply(this);
this.messageZ="this is Z Message";
this.alertZ=function(){
alert(this.messageZ);
};
}
var abjz=new classZ();
objz.alertZ();
abjz.alertX();
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
kzh*_*kzh 16
JavaSript没有真正的多重继承.您只能从一个原型继承,然后复制所需的其余属性.您可以使用instanceof运算符对此进行测试.
在修复错误拼写之后,您的演示工作,但实际上,您并不是真正的继承.要做真正的JS继承:
function A(){}
function B(){}
B.prototype = new A;
b = new B;
console.log(b instanceof A, b instanceof B);
//-> true, true
Run Code Online (Sandbox Code Playgroud)
更多关于MDN上的JS继承
function ctorX() {
this.messageX = "this is X Message";
this.alertX = function() {
console.log(this.messageX);
};
}
function ctorY() {
this.messageY = "this is Y Message";
this.alertY = function() {
console.log(this.messageY);
};
}
function ctorZ() {
ctorX.call(this); // This is the quasi-multiple inheritance
this.messageZ = "this is Z Message";
this.alertZ = function() {
console.log(this.messageZ);
};
}
ctorZ.prototype = new ctorY; // This is the actual inheritance
var objz = new ctorZ();
objz.alertZ();
objz.alertY();
objz.alertX();
console.assert(objz instanceof ctorZ, 'objz is not instance of ctorZ');
console.assert(objz instanceof ctorY, 'objz is not instance of ctorY');
console.assert(objz instanceof ctorX, 'objz is not instance of ctorX');
//The last assert will fail since there is no true multiple inheritance
Run Code Online (Sandbox Code Playgroud)
HMR提出了这样的观点:在某些情况下,用户想要从特定的构造函数继承,但是超级构造函数需要参数并且将失败.绕过这个的方法是创建一个代理构造函数:
function C(x){if(!x) throw new Error;}
function D(){}
function proxyCtor(){/*should be noop*/}
proxyCtor.prototype = C.prototype;
D.prototype = new proxyCtor;
var d = new D;
console.assert(d instanceof C, 'c is not instance of D');
// will err if incorrect, which it's not
Run Code Online (Sandbox Code Playgroud)
你在"alertZ()"的调用中错误拼写了"abjz".
经过更正后,代码工作正常,据我所知(两个警报显示,一个用于Z,一个用于X).
| 归档时间: |
|
| 查看次数: |
8833 次 |
| 最近记录: |