【问题标题】:Can my javascript memoization be more terse?我的 javascript memoization 可以更简洁吗?
【发布时间】:2013-09-10 07:28:04
【问题描述】:

我正在尝试在我的 javascript 中存储对将经常与之交互并使用此代码的页面元素的引用:

var breadcrumbBar = null;
function getBreadcrumbBarElement() {
    if (breadcrumbBar === null) {
        breadcrumbBar = document.getElementById(breadcrumbBarElementId);
    }
    return breadcrumbBar;
}

但是,我想知道我是否可以比这更简洁或惯用(从而更普遍地改进我的 javascript...)?

【问题讨论】:

  • 考虑到document.getElementById可以返回null,使用undefined不是更好吗?

标签: javascript memoization idioms


【解决方案1】:

惯用的方式是使用逻辑 or 运算符:

var breadcrumbBar = null;
function getBreadcrumbBarElement() {
    return breadcrumbBar || (breadcrumbBar = document.getElementById(breadcrumbBarElementId));
}

或者,让它更通用一点:

var elementCache = {}

function getCached(id) {
    return elementCache[id] || (elementCache[id] = document.getElementById(id));
}

【讨论】:

    【解决方案2】:

    或者为了将缓存封装成函数:

    function getCached(id) {
      if (!getCached.elementCache) getCached.elementCache = {}; 
      return getCached.elementCache[id] || (getCached.elementCache[id] = document.getElementById(id));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多