qiuhongbingo / blog

Writing something in Issues.
https://github.com/qiuhongbingo/blog/issues
3 stars 0 forks source link

代理模式在前端中的应用 #28

Open qiuhongbingo opened 4 years ago

qiuhongbingo commented 4 years ago
/**
 * ES next 提供的 Proxy 让我们实现代理模式变得更加容易
 * 我们对函数进行代理,对函数的返回结果进行缓存。在函数执行时,优先使用缓存值,否则返回执行计算值
 */
const getCacheProxy = (fn, cache = new Map()) =>
  new Proxy(fn, {
    apply(target, context, args) {
      const argsString = args.join(' ')
      if (cache.has(argsString)) return cache.get(argsString)
      const result = fn(...args)
      cache.set(argsString, result)
      return result
    }
  })

/**
 * 我们再来看 jQuery 当中的例子
 */
$('button').on('click', function() {
  // 通过 $(this) 可以获取到当前触发事件的元素
  $(this).addClass('active')
  setTimeout(function() {
    // 但是这里的 $( this ) 不再是预期之中的结果
    $(this).addClass('active')
    // 为此,jQuery 提供了 .proxy() 方法,这是典型的代理模式体现
    setTimeout(
      $.proxy(function() {
        $(this).addClass('active')
      }, this),
      500
    )
  })
})