JavaScript的Prototype使用

来源:互联网 发布:linux上传文件的命令 编辑:程序博客网 时间:2024/04/28 12:32

作者:  xuanner  发布日期: 2007-8-23 20:54:41   Email:chenxuan5627@163.com

---------------------------------------------------------------------------------------------------------------

(原创作品,转载请保留作者著作信息)

(1)动态增加对象的属性

语法:类名.prototype.属性名 =  值;

(2)动态增加对象的方法

语法:类名.prototype.方法名 = 已声明的方法;

(3)实现对象的继承

语法:子类.prototype = new 父类();

 例子:

<html>
    
<head>
        
<title>JavaScript中类的继承及动态增加属性和方法</title>
        
<script language="JavaScript">
        
<!--
            
//父类
            function fatherClass(x, y, color) {
                
this.x = x;
                
this.y = y;
                
this.color = color;
            }

            
//子类
            function subClass(r) {
                
this.r = r;
                
this.info = showInfo;
            }

            
//子类的方法
            function showInfo() {
                
var s = this.PI * this.r * this.r;           //使用PI
                document.writeln("半径:"+this.r+"<br>");
                document.writeln(
"面积:" + s+"<br>");
                document.writeln(
"X坐标:"+this.x+"<br>");
                document.writeln(
"Y坐标:"+this.y+"<br>");
                document.writeln(
"颜色:"+this.color+"<br>");
                
this.myMethod();                            //调用myMethod方法
            }

            
            
function dynamicMethod() {
                document.writeln(
"动态增加了一个方法"+"<br>");
            }

            
//继承父类
            subClass.prototype = new fatherClass();       //使subClass继承fatherClass
        //-->
        </script>
    
</head>
    
    
<body>
    
<script language="JavaScript">
        
var sc = new subClass(5);
        subClass.prototype.PI 
= 3.142;                      //动态增加一个属性PI
        subClass.prototype.myMethod = dynamicMethod;      //动态增加一个方法myMethod
        with(sc) {
            x 
= 100;
            y 
= 200;
            color 
= "red";
        }

        sc.info();
    
</script>
    
</body>
</html>
原创粉丝点击