Beyond Sky

I 那屋の琴

博客园 首页 新随笔 联系 订阅 管理
在Javascript程序设计中,时常会用到或新增自己编写的各类函数,随着此类小函数的数量的增加,管理上会比较繁重,如果把基本功能分类封装到各种既有对象或自定义类中去,如Object,Math,String,Number等等,使用的时候会非常的方便,并且更容易理解和管理。

现在已经实现的扩展有Math简单数学函数、模拟实现C++的CPoint的JsPoint类、模拟实现C++的CRect的JsRect矩形类、模拟实现C++的CRgn的JsRange类、对于线条的实现JsLine类等,将会陆续贴出。

下面是对Javascript的Object对象简单功能的扩展,比较实用的是Object.GetProperties()等三个函数,可以遍历对象的所有属性、方法和内在对象,通过类似Object[Object.GetProperties()[n]]( )的形式即可使用:
/*- ==========================================================
*     开发人员:卢印刚
*     编写时间:2006-9-26
*     函数名称:
*     参数说明:
*     功能说明:对Object的扩展
*     使用说明: 1、Object.IsNum(),判断是否为数字
*                            2、Object.IsPoint(),判断是否为Point对象
*                            3、Object.IsRect(),判断是否为Rect对象
*                            4、Object.IsLine(),判断是否为Line对象
*                            5、Object.GetProperties(),返回其属性的数组
*                            6、Object.GetMethods(),返回其方法的数组
*                            7、Object.GetObjects(),返回其对象的数组
*                            8、Object.Decimal( digit ),将数字取小数位
-
*/
Object.prototype.IsNum 
= function()       {    return !isNaN(this);    }
Object.prototype.IsPoint 
= function()       {    
      
return ( this.x != null && this.y != null ) ? true : false;            
}
Object.prototype.IsPointNull 
= function()      {    
      
return ( this.IsPoint() && this.x != 0 && this.y != 0 ) ? true : false;    
}
Object.prototype.IsRect   
= function()      {   
      
return ( this.left==null || this.top==null || this.right==null || this.bottom==null  ) ? false : true;
}
Object.prototype.IsLine 
= function()      {    
      
return ( this.from != null && this.to != null && this.from.IsPoint() && this.to.IsPoint() ) ? true : false;
}    
Object.prototype.GetProperties 
= function()    {
      
var propArr = new Array();
      
for ( prop in this ) {
           
var type = typeof this[prop];
           
if ( type == "string" || type== "number" || type == "boolean" ) propArr.push( prop );
      }
      
return propArr;
}
Object.prototype.GetMethods 
= function()    {
      
var funcArr = new Array();
      
for ( func in this ) {    if ( typeof this[func] == "function" ) funcArr.push( func );    }
      
return funcArr;
}
Object.prototype.GetObjects 
= function()    {
      
var objArr = new Array();
      
for ( obj in this ) {    if ( typeof this[obj] == "object" ) objArr.push( prop );        }
      
return objArr;
}
Object.prototype.Decimal    
= function( digit )    {
      
var number = parseFloat( this.toString() );
      
return Math.round( number*Math.pow( 10, digit ) ) / Math.pow( 10, digit );
}
posted on 2006-09-27 13:08  卢印刚  阅读(760)  评论(5)    收藏  举报