为什么如果超类对象中有事件,则子类中必须用for(var i in PersonC.prototype)来实现继承,而用StudentC.prototype =
华华果果 2012-09-07 11:12:14 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<style>
#div1 {width:100px; height:100px; background:#F00; cursor:move; position:absolute; left:10px; top:10px; border-radius:5px;}
</style>
</head>
<body>
<div id="div1">为什么如果超类对象中有事件,则子类中必须用for(var i in PersonC.prototype)来实现继承,而用StudentC.prototype = new PersonC();原型链继承不可以呢</div>
</body>
</html>
<script>
function PersonC(obj,name,age){
this.oDiv=document.getElementById(obj);
this.name = name;
this.age = age;
this.teacher = '陈老师';
this.aboutMe = function (){ return "我叫" + this.name + "," + this.age + "岁..."};
this.studyEnglish = studyEnglish;
var that= this;
this.oDiv.onmousedown=function(ev){
that.sayHi(ev);
};
}
PersonC.prototype.sex = '男';
PersonC.prototype.sayHi = function(ev){
alert(this.name + "hello boy!");
}
PersonC.prototype.eatFruit = function(){
//alert(this.oDiv);
return this.name + "eat apple....";
}
function studyEnglish(){
return this.name + "study english....";
}
function StudentC(obj,name,age){
PersonC.call(this,obj,name,age);
}
//若使用这种原型链继承方式,则onmousedown事件不起作用
// StudentC.prototype = new PersonC();
//若想使用上面的onmousedown事件,则必须使用下面的原型继承方式
for(var i in PersonC.prototype){
//alert(i);
StudentC.prototype[i]=PersonC.prototype[i];
}
var stu3 = new StudentC('div1','小强',11);
alert(stu3.eatFruit());
</script>