我们先来看一个例子:
function Circle(x,y,r)
{
this.x = x;
this.y = y;
this.r = r;
}
//构造函数的原型是由JavaScript自动创建的
new Circle(0,0,0)
Circle.protorype.pi = 3.1415926;
function Circle_circumference()
{
return 2*this.pi*this.r;
}
Circle.prototype.circumference = Circle_circumference;
Circle.prototype.area = function()
{
return this.pi*this.r*this.r;
}
var c = new Circle(0.0,0.0,0.5);
var a = c.area();
var p = c.circumference();
以上定义了一个构造函数Circle(),用来创建表示圆形的对象,
这个对象的原型变量是Circle.prototype,所以我们可以定义一个对所有Circle对象都有效的常量:Circle.protorype.pi = 3.1415926;
然后通过设置Circle.prototype属性来定义所有的类实例共享的方法:Circle.prototype.circumference = Circle_circumference;
再来看一个例子:
//如果最后一个字符是c,返回true
String.prototype.endsWith = function(c)
{
return ( c == this.charAt(this.length - 1));
}
在String的原型对象中定义了新方法endsWith()后,可以调用如下:
var message = "hello world";
message.endsWith('h') //返回false
message.endsWith('d') //返回true