JavaScript面向对象编程之prototype原型与继承

JavaScript中的类都具有一个原型(prototype)对象, 可以为类的原型对象定义属性,类的实例能够从原型对象处“继承”这些属性。
function  Circle(x,y,r)
{
    
this.x = x;
    
this.y = y;
    
this.r = r;
}

var  wheel  =   new  Circle( 0 , 0 , 5 );
document.write(
" wheel=new Circle(0,0,5);<br/> " );
// 为Circle的prototype设置属性pi
Circle.prototype.pi  =   3.14 ;

function  Circle_circumference()
{
    
return 2*this.pi*this.r;
}

// 为Circle的prototype设置方法Circle_circumference()
Circle.prototype.circumference  =  Circle_circumference;
// wheel自动继承其prototype的属性与方法
var  C1  =  wheel.circumference();
document.write(
" C1= "   +  C1  +   " <br/> " );
// 为wheel设置pi属性后,覆盖了其prototype的属性pi
wheel.pi  =   3.14159 ;
var  C2  =  wheel.circumference();
document.write(
" C2= "   +  C2  +   " <br/> " );
// 删除wheel对象的pi属性,prototype的pi生效
delete  wheel.pi;
var  C3  =  wheel.circumference();
document.write(
" C3= "   +  C3  +   " <br/> " );
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值