在js语言中,每次涉及到工具类封装,都是从网上copy一段,不求甚解。后来发现这种取巧的方式一定程度上降低了工作效率。今天学习js中的class,探索出了一个易用好用的方法,再次总结一下。
ES5 实现
ES5中js没有明确提出class的概念,实现起来有点C语言指针的那么一点意思。
js标准是兼容的,后面的版本可以使用前面的版本。 ES6可以使用ES5语法,ES5不能使用ES6特有语法.
1. 使用函数对象进行工具方法声明
// es5 写法
'use strict'
function FormatUtilES5() {
}
FormatUtilES5.prototype.parseTime = function (time, pattern) {
if (arguments.length === 0 || !time) {
return null
}
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
export {FormatUtilES5}; //方式1.
export default FormatUtilES5 //方式2.
通过 function FormatUtilES5(){} 声明函数对象.
FormatUtilES5.prototype.parseTime 申明需要挂在的函数.
通过export进行导出.
export default 一个js文件只能有一个;方式1 export 可以有多个. 并且export关键字可以和函数定义放到一起 export function FormatUtilES5{}
2. 使用import进行进行导入使用
import {FormatUtilES5} from '@/util/FormatUtilES5' //方式1 对应 export {FormatUtilES5};
import FormatUtilES5 from '@/util/FormatUtilES5' //方式2 对应 export default FormatUtilES5
new 函数对象进行方法调用.
let currentTimeES5 = new FormatUtilES5().parseTime(new Date())
[补充]上面的方法有一定的局限性.可以传递参数, parseTime()里面却无法使用.
思考一下如何保存变量呢? 可以使用闭包的形式!
// es5 写法
'use strict'
function ThrottleUtil() { //可以传递参数
let timer2; //可以变量.throttle 对函数进行进行多次调用
let flag2;
/**
* 节流原理:在一定时间内,只能触发一次
*
* @param {Function} func 要执行的回调函数
* @param {Number} wait 延时的时间
* @param {Boolean} immediate 是否立即执行
* @return null
*/
function throttle(func, wait = 500, immediate = true, timeoutExecute = false) {
// let timeoutExecute //超时函数已经执行过了.
if (immediate) {
if (!flag2) {
flag2 = true
// 如果是立即执行,则在wait毫秒内开始时执行
typeof func === 'function' && func()
timer2 = setTimeout(() => {
flag2 = false
if (!timeoutExecute) {
throttle(func, wait, immediate, true)
}
}, wait)
}
} else if (!flag2) {
flag2 = true
// 如果是非立即执行,则在wait毫秒内的结束处执行
timer2 = setTimeout(() => {
flag2 = false
typeof func === 'function' && func()
if (!timeoutExecute) {
throttle(func, wait, immediate, true)
}
}, wait)
}
}
return {
throttle
}
}
export default ThrottleUtil
import ThrottleUtil from "../../uni_modules/uview-ui/libs/function/ThrottleUtil";
this.throttleObj = new ThrottleUtil();
this.throttleObj.throttle(that.searchSimilar, 2000, false);
this.throttleObj.throttle(that.searchSimilar, 2000, false);
ES6 class 方式
ES6 js明确提出class概念,这和java用起来感觉很像.
使用class进行工具类定义
// es6 写法
'use strict'
class FormatUtilES6 {
constructor(pattern) {
this.pattern = pattern
}
parseTime(time, pattern) {
if (!time) {
return null
}
const format = pattern || this.pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
}
export default FormatUtilES6
使用 class进行类定义
在class内部使用 constructor进行构造函数定义,传入变量(对象范围内可用,使用时添加this关键字) 不需要可以不定义
constructor(pattern) {
this.pattern = pattern
}
使用export进行函数导出.
导入并调用
import FormatUtilES6 from "@/util/FormatUtilES6";
let currentTimeES6 = new FormatUtilES6('{h}:{i}:{s}').parseTime(new Date())