梅开二度 激情超越

~~常用激扬的句子去激励自己的学生,为什么自己却莫名的沉沦了!~~

JScript中prototype属性应用讲解

prototype 属性

返回对象类型原型的引用。

objectName.prototype

objectName 参数是对象的名称。

说明

prototype 属性提供对象的类的一组基本功能。 对象的新实例“继承”赋予该对象原型的操作。

 例如: 要为 Array 对象添加返回数组中最大元素值的方法。 要完成这一点,声明该函数,将它加入 Array.prototype, 并使用它。

				第一种写法:
function array_max( ){

   var i, max = this[0];   for (i = 1; i < this.length; i++)   {   if (max < this[i])   max = this[i];   }   return max;}Array.prototype.max = array_max;

   var i, max = this[0];   for (i = 1; i < this.length; i++)   {   if (max < this[i])   max = this[i];   }   return max;}Array.prototype.max = array_max;

				第二种写法:
Array.prototype.max =function( ){ var i, max = this[0];  
 for (i = 1; i < this.length; i++)  
 {   if (max < this[i])max = this[i]; 
 }  
 return max;}

var x = new Array(1, 2, 3, 4, 5, 6);

var y = x.max( );
alert(y) //返回6

另外几个例子如下:

//日期格式格式化,本例的toString重写了原来的Date对象的toString方法。
//特别注意这个例子,它是重写了原有的一个Date对象的方法。
Date.prototype.toString=function(){
  //获得yy-mm-dd hh-mm-ss这样的格式
  //alert(new Date());
 var date = this;

 var year = date.getFullYear();
 var month = date.getMonth()+1;
 var day  = date.getDate();

 var hours = date.getHours();
 var minutes = date.getMinutes();
 var seconds = date.getSeconds();

 function _f(n){
  if(n<10)
   n = "0"+n;
  return n;
 }

 return year+"-"+_f(month)+"-"+_f(day)+" "+_f(hours)+":"+_f(minutes)+":"+_f(seconds);
}


//计算到今天为止经过了多少天
Date.prototype.daysPassed=function(){
    var date=this;
 if(!(date instanceof Date))
  throw new Error(-1,"错误的参数类型,参数date必须是Date对象的实例。");

 var min  = 1000*60;
 var hour = min*60;
 var day  = hour*24;

 return Math.round(((new Date())-(date))/day);

}


//将当前的数字转换成16进制
Number.prototype.toHex=function(){
 var hexStr = "0123456789ABCDEF";
 var low = this % 16;
 var high = (this - low)/16;
 hex = "" + hexStr.charAt(high) + hexStr.charAt(low);
 return hex;
}

//判断当前串是否已制定的串结尾
String.prototype.endWith=function(str){
 if("string"!=typeof(str))
  throw new Error(-1,"\""+str+"\" 不是一个字符串。");
 return (this.substring(this.length-str.length,this.length)==str);
}

//判断当前串是否已制定的串开头
String.prototype.startWith=function(str){
 if("string"!=typeof(str))
  throw new Error(-1,"\""+str+"\" 不是一个字符串。");
 return (this.substring(0,str.length)==str);
}

//过滤两侧字符串的空格
String.prototype.trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}


//过滤两侧字符串左侧的空格
String.prototype.trim = function()
{
return this.replace(/(^\s*)/g, "");
}


//过滤两侧字符串右侧的空格
String.prototype.trim = function()
{
return this.replace(/(\s*$)/g, "");
}

//给String添加一个方法名字为len,计算字符串的字节长度
String.prototype.len=function()
{
    return this.replace(/[^\x00-\xff]/g,"**").length;
}

posted on 2006-12-19 09:28 梅开二度 激情超越 阅读(739) 评论(0)  编辑 收藏 引用 网摘 所属分类: Javascript


只有注册用户登录后才能发表评论。

My Links

Blog Stats

留言簿(3)

随笔分类(22)

随笔档案(21)

文章分类(48)

文章档案(44)

相册

收藏夹(40)

Favorite site

My Friends

搜索

最新评论