javascript基础教程之对象编程

发布时间:2020-03-04编辑:脚本学堂
本文介绍了javascript中对象编程的相关知识,了解JavaScript基于对象编程,与prototype的使用,有需要的朋友参考下。

例1,javascript 对象编程。
 

复制代码 代码示例:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <title>ObjectDemo--www.jb200.com</title>
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 
   <script language="javascript"> 
   { 
     function student(x,y,z){ 
        this.x=x; 
        this.y=y; 
        this.z=z; 
     } 
     student.prototype.avg=3; 
     function stu_avg(){ 
       return (this.x + this.y + this.z) / this.avg; 
     } 
     student.prototype.stuValue=stu_avg; 
   }  
   </script> 
  </head>
  <body> 
<script language="javascript"> 
{  
var stu=new student(29,25,20); 
var avgValue=stu.stuValue(); 
document.write(avgValue+"<br>"); 
       var stu=new student(29,25,20); 
       stu.avg=1; 
       alert(stu.avg); 
      var avgValue=stu.stuValue(); 
      document.write(avgValue); 
       
   }  
   </script> 
     <br> 
      This is page which test extend object .    
      
     <br> 
  </body> 
</html> 

例2,JavaScript的for加强的使用,for加强只使用于数组和对象中
 

复制代码 代码示例:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <title>ObjectDemo--www.jb200.com</title> 
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 
   <script language="javascript"> 
   { 
     function student(name,age,num){ 
        this.name=name; 
        this.age=age; 
        this.num=num; 
     } 
   }  
</script> 
</head> 
<body> 
<script language="javascript"> 
{   
var stu=new student("xiaobi",25,20092700); 
for(var i in stu){ // usage   
  alert("i"+i); 
  document.write(stu[i]+"<br>"); 

}  
</script> 
<br> 
This is page which test function which name is for in object .    
<br> 
</body> 
</html>