prototype-应用于javascript的内建对象

<一>简要
通过prototype你可以动态的为内建的javascript对象创建方法或者属性.

<二>描述

javascript内建的含有prototype属性的类有以下几种:
Object.prototype: 影响通过new Object(...)构造函数和object{...}创建的对象。更进一步,
所有内建的和用户自定义的并且继承自Object的类都会受到影响。

Array.prototype: 影响通过new Array(...)和[...]构建的数组对象。
String.prototype: 影响通过new String(...)和"..."构建的字符串对象。
Number.prototype: 影响通过new Number(...)和数字赋值构建的数字对象。
Date.prototype: 影响通过new Date(...)构建的日期对象。
Function.prototype:影响通过new Function(...)以及函数定义function(...){....}的函数对象。
RegExp.prototype: 影响通过new RegExp(...)以及/.../方式构建的正则表达式。
Boolean.prototype:布尔对象.

<三>例子:
1.数组为例:有些浏览器可能没有实现数组的分割功能slice(),那么我们通过prototype来实现:
//Only add this implementation if one does not already exist.
if (Array.prototype.slice==null) Array.prototype.slice=function(start,end){
if (start<0) start=this.length+start; //'this' 指向类的实现对象
if (end==null) end=this.length;
else if (end<0) end=this.length+end;
var newArray=[];
for (var ct=0,i=start;i<end;i++) newArray[ct++]=this[i];
return newArray;
}

2.日期为例:自定义日期的格式
Date.prototype.customFormat=function(formatString){
var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhh,hh,h,mm,m,ss,s,ampm,dMod,th;
YY = ((YYYY=this.getFullYear())+"").substr(2,2);
MM = (M=this.getMonth()+1)<10?('0'+M):M;
MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substr(0,3);
DD = (D=this.getDate())<10?('0'+D):D;
DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substr(0,3);
th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);

h=(hhh=this.getHours());
if (h==0) h=24;
if (h>12) h-=12;
hh = h<10?('0'+h):h;
ampm=hhh<12?'am':'pm';
mm=(m=this.getMinutes())<10?('0'+m):m;
ss=(s=this.getSeconds())<10?('0'+s):s;
return formatString.replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm);
}
var now=new Date();
alert("Today is "+now.customFormat('#DDDD#, #MMMM# #D##th#')+"\nThe time is "+now.customFormat('#h#:#mm##ampm#')+".");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值