JS高级编程之模拟常用java类
2014-01-27 21:58
417 查看
前言
你是否遇到过这种情况:在进行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
就这么简单,你学会了吗
相关文章推荐
- js高级编程-Bom
- asp.net 后台常用js方法(编程必备)
- js 高级编程
- js高级编程入门理解
- js高级编程笔记3
- js常用的高级技术
- JS高级表单中几种常用的正则表达式
- js高级编程中命名空间的两种用法
- js高级程序设计--事件模拟
- *Linux Shell 高级编程技巧4----几个常用的shell脚本例子
- js高级编程笔记2
- JS 事件(JS高级程序编程)
- 基于JS高级编程的一些总结
- JS高级编程3-函数柯里化
- Js高级函数式编程
- js 高级编程-属性/变量-访问权限
- JS高级编程4-函数节流
- JavaScript DOM 编程艺术(第二版) 常用JS小脚本
- JAVA常用API或编程工具003--实现pdf在线阅读功能之pdf.js
- 一:js高级编程之:递归