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

function LocalStorageHelper() {
//检测浏览器是否支持localStorage
this.checkIsSupportLS = function () {
return !window.localStorage || true;
}
//根据key获得单个localStorage的值
this.getSingleLS = function (key) {
if (!this.checkIsSupportLS()) { return; }
return window.localStorage.getItem(key);
}
//获取localStorage所有的键值对(返回json对象)
this.getAllLS = function () {
if (!this.checkIsSupportLS()) { return; }
var storage = window.localStorage,
list = [];
for (var i = 0; i < storage.length; i++) {
list[i] = { 'key': storage.key(i), 'value': this.getSingleLS(storage.key(i)) };
}
return list;
}
//创建单个localStorage键值对
this.createSingleLS = function (key, value) {
if (!this.checkIsSupportLS()) { return; }
var storage = window.localStorage;
if (storage.getItem(key)) { this.removeSingleLS(key); }
storage.setItem(key, value);
}
//创建多个localStorage键值对(json对象,格式:[{'key':'','value':''},{'key':'','value':''}])
this.createListLS = function (list) {
if (!this.checkIsSupportLS() || !list) { return; }
var storage = window.localStorage;
for (var i = 0; i < list.length; i++) {
this.createSingleLS(list[i].key, list[i].value);
}
}
//移除单个localStorage键值对
this.removeSingleLS = function (key) {
if (!this.checkIsSupportLS()) { return; }
window.localStorage.removeItem(key);
}
//移除所有localStorage键值对
this.removeAllLS = function () {
if (!this.checkIsSupportLS()) { return; }
window.localStorage.clear();
}
} function CommMethods() { //类似于C#的string.Format()
this.format = function (str, args) {
var result = str;
if (args.length)
for (var i = 0; i < args.length; i++) {
if (typeof (args[i]) != undefined) {
var reg = new RegExp('({[' + i + ']})', 'g');
result = result.replace(reg, args[i]);
}
}
return result;
} //console.log('aaa','type:[log,info,warn,error]':default:log)
this.log = function (msg, type) {
//var _log = console.log;
//console.log = function () {//模糊化输出内容
// _log.call(console, '%c' + [].slice.call(arguments).join(' '), 'color:transparent;text-shadow:0 0 2px rgba(0,0,0,.5);');
//};
var now = new Date(),
y = now.getFullYear(),
m = now.getMonth() + 1,//!js中月份是从0开始的
d = now.getDate(),
h = now.getHours(),
min = now.getMinutes(),
s = now.getSeconds(),
time = this.format('{0}/{1}/{2} {3}:{4}:{5}', [y, m, d, h, min, s]),
outMsg = this.format('{0}> {1}', [time, msg ? msg : '']);
switch (type) {
case 'log':
console.log(outMsg);
break;
case 'info':
console.info(outMsg)
break;
case 'warn':
console.warn(outMsg);
break;
case 'error':
console.error(outMsg);
break;
default:
console.log(outMsg);
break;
}
} //检测是否为正数
this.isPositiveNumber = function (a) {
var reg = /^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
return reg.test(a);
} //检测是否为数字--(数字包含小数)--
this.isNumber = function (a) {
return !isNaN(a);
} //检测是否为整数
this.isInt = function (a) {
var reg = /^(-|\+)?\d+$/;
return reg.test(a);;
} //检测是否为有效的长日期格式 - "YYYY-MM-DD HH:MM:SS" || "YYYY/MM/DD HH:MM:SS"
this.isDateTime = function (str) {
var result = str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
if (result == null) return false;
var d = new Date(result[1], result[3] - 1, result[4], result[5], result[6], result[7]);
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]);
} //检测是否为 YYYY-MM-DD || YYYY/MM/DD 的日期格式
this.isDate = function (str) {
var result = str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if (result == null) return false;
var d = new Date(result[1], result[3] - 1, result[4]);
return (d.getFullYear() == result[1] && d.getMonth() + 1 == result[3] && d.getDate() == result[4]);
} //检测是否为有效的电子邮件
this.isEmail = function (str) {
var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
return reg.test(str);
} //去除字符串的首尾的空格
this.trim = function (str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
} //返回字符串的实际长度, 一个汉字算2个长度
this.strRealLength = function (str) {
return str.replace(/[^\x00-\xff]/g, "**").length;
} //检测是否为中国邮政编码(6位)
this.isPostCode = function (str) {
var reg = /[1-9]\d{5}(?!\d)/;
return reg.test(str);
} //检测是否为国内座机电话号码(0511-4405222 或 021-87888822)
this.isTellPhone = function (str) {
var reg = /\d{3}-\d{8}|\d{4}-\d{7}/;
return reg.test(str);
} //检测是否为腾讯QQ号
this.isQQ = function (str) {
var reg = /\d{15}|\d{18}/;
return reg.test(str);
} //检测是否为身份证(15位或18位)
this.isIDCard = function (str) {
var len = this.strRealLength(str),
reg15 = /\d{15}|\d{18}/,
reg18 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
if (len === 15) {
return reg15.test(str);
}
else if (len === 18) {
return reg18.test(str);
}
else { return false; }
} //检测文本是否为空
this.checkIsNull = function (a) {
return (a == '' || a == null || typeof (a) == undefined);
} //XML转成JSON
this.xmlToJson = function (xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof (obj[nodeName].length) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
} //去除数组重复项
this.removeListRepeat = function (list) {
var $ = list,
o1 = {},
o2 = {},
o3 = [],
o; for (var i = 0; o = $[i]; i++) {
if (o in o1) {
if (!(o in o2)) o2[o] = o;
delete $[i];
} else {
o1[o] = o;
}
} $.length = 0; for (o in o1) {
$.push(o);
} for (o in o2) {
o3.push(o);
} return o3; } } function CookieHelper() {
// 1. 设置COOKIE // 简单型
this.setCookieSimple = function (c_name, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
} // 完整型
this.setCookieBoth = function (name, value, expires, path, domain, secure) {
var expDays = expires * 24 * 60 * 60 * 1000,
expDate = new Date();
expDate.setTime(expDate.getTime() + expDays);
var expString = ((expires == null) ? '' : (';expires=' + expDate.toGMTString())),
pathString = ((path == null) ? '' : (";path=" + path)),
domainString = ((domain == null) ? '' : (';domain=' + domain)),
secureString = ((secure == true) ? ';secure' : '');
document.cookie = name + "=" + escape(value) + expString + pathString + domainString + secureString;
} // 2.获取指定名称的cookie值:
this.getCookie = function (c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + '=')
if (c_start != -1) {
c_start = c_start + c_name.length + 1
c_end = document.cookie.indexOf(';', c_start)
if (c_end == -1) c_end = document.cookie.length
return unescape(document.cookie.substring(c_start, c_end))
}
}
return ''
} // 3.删除指定名称的cookie:
this.removeCookie = function (name) {
var expDate = new Date();
expDate.setTime(expDate.getTime() - 100);
document.cookie = name + '=;expires=' + expDate.toGMTString();
} // 4. 检测cookie:
this.checkIsSupportCookie = function () {
var result = false;
if (navigator.cookiesEnabled) {return true; }
document.cookie = 'testcookie=yes;';
var setCookie = document.cookie;
if (setCookie.indexOf('testcookie=yes') > -1) {
result = true;
} else {
document.cookie = '';
}
return result;
} } $(function () {
var localstoragehelper = new LocalStorageHelper();
var commmethod = new CommMethods();
localstoragehelper.checkIsSupportLS();
commmethod.checkIsNull();
});

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. 泛型,迭代器,LinkedList<E>

    1 <e>里面只能填类,不能用基本数据类型,不过integer 这样的的也行 2在模板类(泛型类中)class demo<e>由于不知道e是那个,所有通常都是重写大家都有的to ...

  2. 如何遍历json属性和动态添加属性

    var person= { name: 'zhangsan', pass: '123' , 'sni.ni' : 'sss', hello:function (){ for(var i=0;i< ...

  3. sql批量插入数据之存储过程

    -- ============================================= -- Author: jf_ou -- Create date: 2016/03/22 -- Desc ...

  4. 如何搭建一个angularJS应用

    以写一个hello word为例,首先引入angular.js库文件   <!doctype html> <html ng-app> <head> <titl ...

  5. PHP 读取/导出 CSV文件

    工作中经常会有遇到导入/导出的需求,下面是常用的方法.读取CSV文件,可以分页读取,设置读取行数,起始行数即可.导出CSV文件,用两种方法进行实现. /** * 读取CSV文件 * @param st ...

  6. nginx反向代理取得IP地址

    nginx反向代理后,在应用中取得的ip都是反向代理服务器的ip,取得的域名也是反向代理配置的url的域名,解决该问题,需要在nginx反向代理配置中添加一些配置信息,目的将客户端的真实ip和域名传递 ...

  7. python使用platform模块获取系统环境并去除换行符

    近来在porting一个网站,企图拿到这个网站的数据来做分析.为了支持多系统环境的正常运行.需要知道当前系统环境的是什么OS? 1.python内置platform库.可以很方便得到当前系统环境时什么 ...

  8. 转:Centos6.3添加解码器播放MP3和常见视频音频

    原文来自于:http://blog.csdn.net/odaynot/article/details/8462273 参考地址: http://wiki.centos.org/AdditionalRe ...

  9. XML SAX解析

    SAX是一种占用内存少且解析速度快的解析器,它采用的是事件驱动,它不需要解析完整个文档,而是按照内容顺序,看文档某个部分是否符合xml语法,如果符合就触发相应的事件.所谓的事件就是些回调方法( cal ...

  10. java四种创建对象的方法

    1.用new语句创建对象,这是最常见的创建对象的方法.   2.运用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor类的newInstance ...