JS高级编程之模拟常用java类

来源:互联网 发布:java定义构造方法 编辑:程序博客网 时间:2024/06/01 16:52

前言


你是否遇到过这种情况:在进行javascript编程的时候,想要拼接一个很长的字符串,如果你依然使用“+”操作符进行处理,说明你真的很业余;也许聪明的你会想到java中有一个叫StringBuilder的类专门用来处理字符串拼接,javascript中是否也有类似的类呢?很遗憾javascript没有提供类似的类。



能够想到使用StringBuilder是最重要的,js没提供,我们自己写一个不就行了。然后将这个StringBuilder类储存到自己的js代码库里(就是一个.js文件),以后要使用类似的功能直接引一个js文件就可以了。

 

js是一门非常灵活的语言,我们可以用原生js模拟很多java中的类,然后将这些“类”(其实是函数)放到一个.js文件中作为自己的代码库就可以了。

 

 

下面我就为大家举一些例子来说明如何使用js来模拟常用的java


实战


StringBuilder

/*StringBuilder字符串拼接类*/function StringBuilder(){this.str_array=new Array();}//为其添加append方法StringBuilder.prototype.append=function(data){this.str_array.push(data);return this;}//为其添加toString方法StringBuilder.prototype.toString=function(){return this.str_array.join('');}

使用示例

var builder=new StringBuilder ();var name="wh";builder.append('这篇博客是 ').append(name).append('写的');alert(builder.toString());


HashMap

/*HashMap类*/function HashMap(){this.entryArray=new Array();}//put函数HashMap.prototype.put=function(key,value){var obj=this.get(key);if(obj==null){this.entryArray.push({key:key,value:value,getKey:function(){return key;},getValue:function(){return value;}});}else{for(var index in this.entryArray){if(this.entryArray[index].key==key){this.entryArray[index].value=value;}}}}//get函数HashMap.prototype.get=function(key){var value=null;for(var index in this.entryArray){if(this.entryArray[index].key==key){value=this.entryArray[index].value;break;}}return value;}//clear函数HashMap.prototype.clear=function(){this.entryArray=new Array();}//putAll函数HashMap.prototype.putAll=function(map){if(map instanceof HashMap){for(var index in map.entryArray){this.put(map.entryArray[index].key,map.entryArray[index].value);}}}//entrySet函数HashMap.prototype.entrySet=function(){return this.entryArray;}//keySet函数HashMap.prototype.keySet=function(){var keyArray=new Array();for(var index in this.entryArray){keyArray.push(this.entryArray[index].key);}return keyArray;}//values函数HashMap.prototype.values=function(){var valueArray=new Array();for(var index in this.entryArray){valueArray.push(this.entryArray[index].value);}return valueArray;}


由上我们可以看出

利用[]{}等已有数据结构去存储数据,[]+{}形成的json数据结构可以模拟各种数据结构;

定义一个函数作为“类”,如:StringBuilder,其内部要有一个数据结构用来存储数据

在“类”的prototype对象上添加方法,如append

 

就这么简单,你学会了吗


1 0