JavaScript的Prototype使用

作者:  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 >
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值