原型对象和继承(javascript)

我们先来看一个例子:

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值