最近接触小程序开发,有几个疑惑点,本文算是其中之一。
工具类的使用,官方自动生成的案例是这样子的:
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime
}
这就决定了每次写一个方法都需要放到exports里面导出才能使用,毕竟工具类就是需要在其他地方多次调用的,没搞明白为啥要搞的这么繁琐。
改进后这样子写:
class Util {
constructor() {}
formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
}
module.exports = Util
这样只需要将类名导出即可,在文件中可以这样子使用:
const UtilFile = require('../../utils/util2.js')
const Util = new UtilFile()
var res = Util.formatNumber(2222)
console.log(res)
这样不需要每次写一个方法就要想着导出,导出类即可以导出其类的所有方法。
没想明白官方为啥要那样子搞。