您的位置:首页 > Web前端 > JavaScript

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

2007-12-10 16:58 686 查看
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/>");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: