helper.js 1.64 KB
/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: limin
 * @Date: 2021-07-21 17:20:56
 * @LastEditors: limin
 * @LastEditTime: 2021-08-06 16:47:13
 * @FilePath: \account\js\helper.js
 */
layui.define(['store'], function (exports) {
  /**深度合并对象 */
  function clone() {
    var extended = {}
    var deep = false
    var i = 0

    // 判断是否为深拷贝
    if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]') {
      deep = arguments[0]
      i++ //如果为深拷贝则初始的i为1或者为0
    }

    // 将对象属性合并到已存在的对象中
    var merge = function (obj) {
      for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
          // 如果属性为对象并且需要深拷贝时则使用函数递归、反之则将当前的属性替换现有的属性
          if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {
            extended[prop] = clone(extended[prop], obj[prop])
          } else {
            extended[prop] = obj[prop]
          }
        }
      }
    }
    // 遍历所有对象属性
    for (; i < arguments.length; i++) {
      merge(arguments[i])
    }
    return extended
  }

  function debounce(fun, delay) {
    return function (args) {
        //获取函数的作用域和变量
        let that = this
        let _args = args
        //每次事件被触发,都会清除当前的timeer,然后重写设置超时调用
        clearTimeout(fun.id)
        fun.id = setTimeout(function () {
            fun.call(that, _args)
        }, delay)
    }
}
  exports('helper', {
    clone: clone,
    store: layui.store,
    debounce: debounce
  })
})