<!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>

解决方案 »

  1.   

    你搞错了,不是继承失败
    是你的代码出错了,你也没发觉?
    StudentC.prototype = new PersonC();因为你没有传参数,PersonC函数将会出错
    this.oDiv.onmousedown=function(ev){   
      that.sayHi(ev);   
      };
    这句会出错,因为没有传参数this.oDiv获取的是null或undefined,你不能给空值添加成员。当然由于原型链上的成员和对象自身添加的成员有点区别,即使原型链上的该成员添加失败,构造函数中的还是成功了的,所以实际这个成员应该可以访问,只是由于代码出现未处理异常中断了而已。
    改成:
    if(this.oDiv)
    {
      this.oDiv.onmousedown=function(ev){   
      that.sayHi(ev);   
      };
    }
    就可以了