JS prototype方法应用

来源:互联网 发布:拉里约翰逊数据 编辑:程序博客网 时间:2024/06/05 16:26

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Property </TITLE>
<script langugage="javaScript">
/**********************************************HashMap*************************************************************/
/**
 *定义一个Map 对象
*/
 function HashMap(){
 this.length=0;
 this.prefix = "hashmap_prefix_20050524_";
}
/**
* 向HashMap中添加键值对
*/
HashMap.prototype.put = function (key, value)
{
     this[this.prefix + key] = value;
     this.length ++;
}
/**
* 向HashMap中通过键值取到对应的值
*/
HashMap.prototype.get = function(key)
{
     return typeof this[this.prefix + key] == "undefined"
             ? null : this[this.prefix + key];
}
/**
* 判断HashMap是否存在某个key
*/
HashMap.prototype.containsKey = function(key)
{
     for(var strKey in this)
     {
        if(strKey == this.prefix + key)
           return true; 
     }
     return false;
}
/**
* 判断HashMap是否存在某个value
*/
HashMap.prototype.containsValue = function(value)
{
     for(var strKey in this)
     {
        if(this[strKey] == value)
           return true; 
     }
     return false;
}

//调用方法
function mapMethod(){
 var map = new HashMap();
 map.put("key1",0001);
 map.put("key2",0002);
 map.put("key3",0003);
 map.put("key4",0004);
 var key1 = new String("key1");
 var key8 = new String("key8");
 alert(map.containsKey(key1));
 alert(map.containsKey(key8));
 alert(map.get("key1"));
 alert(map.get("key8"));
}
/*************************************************Number*******************************************************/
/**
* Number 对象的加法运算
*/
Number.prototype.add = function(num){
 return(this+num);
}
/**
* Number 对象的减法运算
*/
Number.prototype.sub = function(num){
 return (this-num);
}
/**
* Number 对象的乘法运算
*/
Number.prototype.multi = function(num){
 return (this*num);
}
/**
* Number 对象的除法运算
*/
Number.prototype.divi = function(num){
 if(num == 0){
  return ("被除数分母不能为0");
 } else {
  return (this/num);
 }
}

//调用方法
function numMethod(){
 var count = new Number(12);
 alert(count.add(23));
 alert(count.sub(342));
 alert(count.multi(0));
 alert(count.divi(0));
}
</script>
</HEAD>
<BODY>
<table cellpadding=0 cellspacing=0 border=0>
 <tr><td>操作Map: </td><td><input type="button" value="operatorMap" onClick="mapMethod();"/></td></tr>
 <tr><td>操作Number: </td><td><input type="button" value="operatorNum" onClick="numMethod();"/></td></tr>
</table>
</table
</BODY>
</HTML>