将js方法封装成类,好处就是团队开发中避免命名冲突,部分类整理代码如下:

  1. function LocalStorageHelper() {
  2. //检测浏览器是否支持localStorage
  3. this.checkIsSupportLS = function () {
  4. return !window.localStorage || true;
  5. }
  6. //根据key获得单个localStorage的值
  7. this.getSingleLS = function (key) {
  8. if (!this.checkIsSupportLS()) { return; }
  9. return window.localStorage.getItem(key);
  10. }
  11. //获取localStorage所有的键值对(返回json对象)
  12. this.getAllLS = function () {
  13. if (!this.checkIsSupportLS()) { return; }
  14. var storage = window.localStorage,
  15. list = [];
  16. for (var i = 0; i < storage.length; i++) {
  17. list[i] = { 'key': storage.key(i), 'value': this.getSingleLS(storage.key(i)) };
  18. }
  19. return list;
  20. }
  21. //创建单个localStorage键值对
  22. this.createSingleLS = function (key, value) {
  23. if (!this.checkIsSupportLS()) { return; }
  24. var storage = window.localStorage;
  25. if (storage.getItem(key)) { this.removeSingleLS(key); }
  26. storage.setItem(key, value);
  27. }
  28. //创建多个localStorage键值对(json对象,格式:[{'key':'','value':''},{'key':'','value':''}])
  29. this.createListLS = function (list) {
  30. if (!this.checkIsSupportLS() || !list) { return; }
  31. var storage = window.localStorage;
  32. for (var i = 0; i < list.length; i++) {
  33. this.createSingleLS(list[i].key, list[i].value);
  34. }
  35. }
  36. //移除单个localStorage键值对
  37. this.removeSingleLS = function (key) {
  38. if (!this.checkIsSupportLS()) { return; }
  39. window.localStorage.removeItem(key);
  40. }
  41. //移除所有localStorage键值对
  42. this.removeAllLS = function () {
  43. if (!this.checkIsSupportLS()) { return; }
  44. window.localStorage.clear();
  45. }
  46. }
  47.  
  48. function CommMethods() {
  49.  
  50. //类似于C#的string.Format()
  51. this.format = function (str, args) {
  52. var result = str;
  53. if (args.length)
  54. for (var i = 0; i < args.length; i++) {
  55. if (typeof (args[i]) != undefined) {
  56. var reg = new RegExp('({[' + i + ']})', 'g');
  57. result = result.replace(reg, args[i]);
  58. }
  59. }
  60. return result;
  61. }
  62.  
  63. //console.log('aaa','type:[log,info,warn,error]':default:log)
  64. this.log = function (msg, type) {
  65. //var _log = console.log;
  66. //console.log = function () {//模糊化输出内容
  67. // _log.call(console, '%c' + [].slice.call(arguments).join(' '), 'color:transparent;text-shadow:0 0 2px rgba(0,0,0,.5);');
  68. //};
  69. var now = new Date(),
  70. y = now.getFullYear(),
  71. m = now.getMonth() + 1,//!js中月份是从0开始的
  72. d = now.getDate(),
  73. h = now.getHours(),
  74. min = now.getMinutes(),
  75. s = now.getSeconds(),
  76. time = this.format('{0}/{1}/{2} {3}:{4}:{5}', [y, m, d, h, min, s]),
  77. outMsg = this.format('{0}> {1}', [time, msg ? msg : '']);
  78. switch (type) {
  79. case 'log':
  80. console.log(outMsg);
  81. break;
  82. case 'info':
  83. console.info(outMsg)
  84. break;
  85. case 'warn':
  86. console.warn(outMsg);
  87. break;
  88. case 'error':
  89. console.error(outMsg);
  90. break;
  91. default:
  92. console.log(outMsg);
  93. break;
  94. }
  95. }
  96.  
  97. //检测是否为正数
  98. this.isPositiveNumber = function (a) {
  99. var reg = /^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
  100. return reg.test(a);
  101. }
  102.  
  103. //检测是否为数字--(数字包含小数)--
  104. this.isNumber = function (a) {
  105. return !isNaN(a);
  106. }
  107.  
  108. //检测是否为整数
  109. this.isInt = function (a) {
  110. var reg = /^(-|\+)?\d+$/;
  111. return reg.test(a);;
  112. }
  113.  
  114. //检测是否为有效的长日期格式 - "YYYY-MM-DD HH:MM:SS" || "YYYY/MM/DD HH:MM:SS"
  115. this.isDateTime = function (str) {
  116. var result = str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
  117. if (result == null) return false;
  118. var d = new Date(result[1], result[3] - 1, result[4], result[5], result[6], result[7]);
  119. return (d.getFullYear() == result[1] && (d.getMonth() + 1) == result[3] && d.getDate() == result[4] && d.getHours() == result[5] && d.getMinutes() == result[6] && d.getSeconds() == result[7]);
  120. }
  121.  
  122. //检测是否为 YYYY-MM-DD || YYYY/MM/DD 的日期格式
  123. this.isDate = function (str) {
  124. var result = str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
  125. if (result == null) return false;
  126. var d = new Date(result[1], result[3] - 1, result[4]);
  127. return (d.getFullYear() == result[1] && d.getMonth() + 1 == result[3] && d.getDate() == result[4]);
  128. }
  129.  
  130. //检测是否为有效的电子邮件
  131. this.isEmail = function (str) {
  132. var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
  133. return reg.test(str);
  134. }
  135.  
  136. //去除字符串的首尾的空格
  137. this.trim = function (str) {
  138. return str.replace(/(^\s*)|(\s*$)/g, "");
  139. }
  140.  
  141. //返回字符串的实际长度, 一个汉字算2个长度
  142. this.strRealLength = function (str) {
  143. return str.replace(/[^\x00-\xff]/g, "**").length;
  144. }
  145.  
  146. //检测是否为中国邮政编码(6位)
  147. this.isPostCode = function (str) {
  148. var reg = /[1-9]\d{5}(?!\d)/;
  149. return reg.test(str);
  150. }
  151.  
  152. //检测是否为国内座机电话号码(0511-4405222 或 021-87888822)
  153. this.isTellPhone = function (str) {
  154. var reg = /\d{3}-\d{8}|\d{4}-\d{7}/;
  155. return reg.test(str);
  156. }
  157.  
  158. //检测是否为腾讯QQ号
  159. this.isQQ = function (str) {
  160. var reg = /\d{15}|\d{18}/;
  161. return reg.test(str);
  162. }
  163.  
  164. //检测是否为身份证(15位或18位)
  165. this.isIDCard = function (str) {
  166. var len = this.strRealLength(str),
  167. reg15 = /\d{15}|\d{18}/,
  168. reg18 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
  169. if (len === 15) {
  170. return reg15.test(str);
  171. }
  172. else if (len === 18) {
  173. return reg18.test(str);
  174. }
  175. else { return false; }
  176. }
  177.  
  178. //检测文本是否为空
  179. this.checkIsNull = function (a) {
  180. return (a == '' || a == null || typeof (a) == undefined);
  181. }
  182.  
  183. //XML转成JSON
  184. this.xmlToJson = function (xml) {
  185. // Create the return object
  186. var obj = {};
  187. if (xml.nodeType == 1) { // element
  188. // do attributes
  189. if (xml.attributes.length > 0) {
  190. obj["@attributes"] = {};
  191. for (var j = 0; j < xml.attributes.length; j++) {
  192. var attribute = xml.attributes.item(j);
  193. obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
  194. }
  195. }
  196. } else if (xml.nodeType == 3) { // text
  197. obj = xml.nodeValue;
  198. }
  199. // do children
  200. if (xml.hasChildNodes()) {
  201. for (var i = 0; i < xml.childNodes.length; i++) {
  202. var item = xml.childNodes.item(i);
  203. var nodeName = item.nodeName;
  204. if (typeof (obj[nodeName]) == "undefined") {
  205. obj[nodeName] = xmlToJson(item);
  206. } else {
  207. if (typeof (obj[nodeName].length) == "undefined") {
  208. var old = obj[nodeName];
  209. obj[nodeName] = [];
  210. obj[nodeName].push(old);
  211. }
  212. obj[nodeName].push(xmlToJson(item));
  213. }
  214. }
  215. }
  216. return obj;
  217. }
  218.  
  219. //去除数组重复项
  220. this.removeListRepeat = function (list) {
  221. var $ = list,
  222. o1 = {},
  223. o2 = {},
  224. o3 = [],
  225. o;
  226.  
  227. for (var i = 0; o = $[i]; i++) {
  228. if (o in o1) {
  229. if (!(o in o2)) o2[o] = o;
  230. delete $[i];
  231. } else {
  232. o1[o] = o;
  233. }
  234. }
  235.  
  236. $.length = 0;
  237.  
  238. for (o in o1) {
  239. $.push(o);
  240. }
  241.  
  242. for (o in o2) {
  243. o3.push(o);
  244. }
  245.  
  246. return o3;
  247.  
  248. }
  249.  
  250. }
  251.  
  252. function CookieHelper() {
  253. // 1. 设置COOKIE
  254.  
  255. // 简单型
  256. this.setCookieSimple = function (c_name, value, expiredays) {
  257. var exdate = new Date();
  258. exdate.setDate(exdate.getDate() + expiredays);
  259. document.cookie = c_name + "=" + escape(value) +
  260. ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
  261. }
  262.  
  263. // 完整型
  264. this.setCookieBoth = function (name, value, expires, path, domain, secure) {
  265. var expDays = expires * 24 * 60 * 60 * 1000,
  266. expDate = new Date();
  267. expDate.setTime(expDate.getTime() + expDays);
  268. var expString = ((expires == null) ? '' : (';expires=' + expDate.toGMTString())),
  269. pathString = ((path == null) ? '' : (";path=" + path)),
  270. domainString = ((domain == null) ? '' : (';domain=' + domain)),
  271. secureString = ((secure == true) ? ';secure' : '');
  272. document.cookie = name + "=" + escape(value) + expString + pathString + domainString + secureString;
  273. }
  274.  
  275. // 2.获取指定名称的cookie值:
  276. this.getCookie = function (c_name) {
  277. if (document.cookie.length > 0) {
  278. c_start = document.cookie.indexOf(c_name + '=')
  279. if (c_start != -1) {
  280. c_start = c_start + c_name.length + 1
  281. c_end = document.cookie.indexOf(';', c_start)
  282. if (c_end == -1) c_end = document.cookie.length
  283. return unescape(document.cookie.substring(c_start, c_end))
  284. }
  285. }
  286. return ''
  287. }
  288.  
  289. // 3.删除指定名称的cookie:
  290. this.removeCookie = function (name) {
  291. var expDate = new Date();
  292. expDate.setTime(expDate.getTime() - 100);
  293. document.cookie = name + '=;expires=' + expDate.toGMTString();
  294. }
  295.  
  296. // 4. 检测cookie:
  297. this.checkIsSupportCookie = function () {
  298. var result = false;
  299. if (navigator.cookiesEnabled) {return true; }
  300. document.cookie = 'testcookie=yes;';
  301. var setCookie = document.cookie;
  302. if (setCookie.indexOf('testcookie=yes') > -1) {
  303. result = true;
  304. } else {
  305. document.cookie = '';
  306. }
  307. return result;
  308. }
  309.  
  310. }
  311.  
  312. $(function () {
  313. var localstoragehelper = new LocalStorageHelper();
  314. var commmethod = new CommMethods();
  315. localstoragehelper.checkIsSupportLS();
  316. commmethod.checkIsNull();
  317. });

js类封装的更多相关文章

  1. JS类的封装及实现代码

    js并不是一种面向对向的语言, 没有提供对类的支持, 因此我们不能像在传统的语言里那样 用class来定义类, 但我们可以利用js的闭包封装机制来实现js类, 我们来封装一个简的Shape类. 1. ...

  2. js创建类(封装)

    js如何创建类(封装)     学过其他面向对象语言的JavaScripter,可能都应用过类,如:class{},等定义的一系列方法, 但是初学者看是学习js的时候,经常会看到这样一句话,那就是Ja ...

  3. JS 对象封装的常用方式

    JS是一门面向对象语言,其对象是用prototype属性来模拟的,下面,来看看如何封装JS对象. 常规封装 function Person (name,age,sex){ this.name = na ...

  4. 自己手写的自动完成js类

    在web开发中,为了提高用户体验,会经常用到输入框的自动完成功能,不仅帮助用户进行快速输入,最重要的是帮助那些“记不全要输入什么”的用户进行选择.这个功能有很多插件已经实现了,为了适应项目的特殊需求, ...

  5. js类(继承)(二)

    1. 定义js类 js并不是一种面向对向的语言, 没有提供对类的支持, 因此我们不能像在传统的语言里那样 用class来定义类, 但我们可以利用js的闭包封装机制来实现js类, 我们来封装一个简的Sh ...

  6. JS类继承常用方式发展史

    JS类继承常用方式发展史 涉及知识点 构造函数方式继承 1-继承单个对象 1.1 多步走初始版 1.2 多步走优化版 1.3 Object.create()方式 2-继承多个对象 2.1 遍历 Obj ...

  7. .Net Core ORM选择之路,哪个才适合你 通用查询类封装之Mongodb篇 Snowflake(雪花算法)的JavaScript实现 【开发记录】如何在B/S项目中使用中国天气的实时天气功能 【开发记录】微信小游戏开发入门——俄罗斯方块

    .Net Core ORM选择之路,哪个才适合你   因为老板的一句话公司项目需要迁移到.Net Core ,但是以前同事用的ORM不支持.Net Core 开发过程也遇到了各种坑,插入条数多了也特别 ...

  8. ASP.NET MVC深入浅出(被替换) 第一节: 结合EF的本地缓存属性来介绍【EF增删改操作】的几种形式 第三节: EF调用普通SQL语句的两类封装(ExecuteSqlCommand和SqlQuery ) 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法 第六节: EF高级属性(二) 之延迟加载、立即加载、显示加载(含导航属性) 第十节: EF的三种追踪

    ASP.NET MVC深入浅出(被替换)   一. 谈情怀-ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态 ...

  9. 使用jq把js代码封装一个自己的插件

    为什么要把js功能封装成插件呢?我觉得有以下几点吧 1.最基本的原因就是便于代码复用. 2.便于维护和管理. 3.提升自身的能力. 4.避免各个相同功能组件的干扰,以及一些作用域会相互影响的问题. j ...

随机推荐

  1. 二十分钟弄懂C++11 的 rvalue reference (C++ 性能剖析 (5))

    C++ 11加了许多新的功能.其中对C++性能和我们设计class的constructor或assignment可能产生重大影响的非rvalue reference莫属!我看了不少资料,能说清它的不多 ...

  2. php小知识点

    1.字符串可以里面的字符可以像数组一样访问,比如$s = "123";$s[1]就等于2,如果字符串为中文则会乱码,需要使用mb_substr进行截取: 2.php中的单引号(' ...

  3. Linux下的Job Control(转:http://blog.chinaunix.net/uid-26495963-id-3062757.html)

    一.Job的概念 Job是指在批处理的环境中,为完成某一任务而进行一系列操作的总称.在个人接触计算机的年代,批处理的环境已经不容见到了,只有一些特殊的行业和环境下还在使用这样的概念,仅在书本中接触过. ...

  4. QComboBox实现复选功能

    需求: 下拉列表有复选功能 不可编辑 显示所有选中项   关于QComboBox的复选功能有几种方案: QStandardItemModel + QStandardItem QListWidget + ...

  5. MySql存储过程—2、第一个MySql存储过程的建立

    看看如何创建一个存储过程.虽然通过命令行可以创建,但基本通过MySQL提供的Query browser来创建. 1.首先我们通过Administrator在test数据库中创建一个简单的表名叫”pro ...

  6. iOS开发网络篇-JSON文件的解析

    一.什么是JSON数据 1.JSON的简单介绍 JSON:是一种轻量级的传输数据的格式,用于数据的交互 JSON是javascript语言的一个子集.javascript是个脚本语言(不需要编译),用 ...

  7. FileUpload 改变控件显示的文字

    浏览

  8. C语言字符数组越界现象

    今天在用C的过程中发现一个奇怪的现象.代码如下: ]; chs[] = 'a'; chs[] = 'b'; printf(]); 结果 输出 是  a. 在网上查了一下.有个网友是这样回答的: “ 我 ...

  9. Hadoop 学习笔记(一) HDFS API

    http://www.cnblogs.com/liuling/p/2013-6-17-01.html 这个也不错http://www.teamwiki.cn/hadoop/thrift thrift编 ...

  10. 【转】带checkbox的ListView实现(二)——自定义Checkable控件的实现方法

    原文网址:http://blog.csdn.net/harvic880925/article/details/40475367 前言:前一篇文章给大家展示了传统的Listview的写法,但有的时候我们 ...