函数内部命名函数表达式的模式

Fel*_*ger 0 javascript function jestjs

以下代码摘自Jest源代码:

function _path() {
  const data = _interopRequireDefault(require('path'));

  _path = function _path() {
    return data;
  };

  return data;
}
Run Code Online (Sandbox Code Playgroud)

为什么在中间有命名函数表达式?该模式如何以及何时使用?

VLA*_*LAZ 6

外部函数称为_path。然后在其内部,该行用另一个称为的函数_path = function _path()覆盖_path变量(当前分配给该_path函数)_path

因此,执行该功能时,该功能会用新功能覆盖自身,而新功能会执行其他操作。这是此原理的简单说明:

function f() {
  console.log("outer");
  f = function f() {
    console.log("inner");
  }
}

f(); //outer
f(); //inner
f(); //inner
Run Code Online (Sandbox Code Playgroud)

所以,这是什么它做。至于为什么这样做-缓存。它只需要查找/计算一个值一次,然后将缓存所有其他执行。因此,这是lookup一个网络操作的模拟替代品的示例。

function lookup() {
  console.log("making a network call");
  return 4;
}

function f() {
  var output = lookup();

  f = function f() {
    return output;
  }
  
  return output;
}

console.log(f()); //network call -> 4
console.log(f()); //4
console.log(f()); //4
Run Code Online (Sandbox Code Playgroud)

对于不需要网络调用的繁重计算,也可以执行相同的操作-只能重复计算一次,而不必重复计算并每次都用完CPU周期。

最后,为什么调用内部函数_path-没有严格的理由调用它。即使没有名称,该代码也可以正常工作。但是,它确实替代了外部函数,因此保留名称是一个好主意。当您看到堆栈跟踪时,它也可以帮助调试。

通常,此技术称为备忘录。旁注:这是正确的拼写,没有r。尽管我怀疑如果您将它放入任何人都会感到困惑。

无论如何,记忆化涉及一次计算一个函数,而每隔两次仅返回一次结果。一种通用方法是拥有一个memoize可以装饰其他功能的功能。这是一个示例实现:

function memoize(func) {
  //keep a cache for all results
  const cache = {};
  
  //make a new function
  const memo = function() {
    //get the arguments from the input
    var key = JSON.stringify(...arguments);

    let result;
    if (cache.hasOwnProperty(key)) {
      //get result from cache
      result = cache[key];
    } else {
      //calculate the result and put it in the cache
      result = func(...arguments);
      cache[key] = result;
    }

    return result;
  }
  
  return memo;
}

function lookup(data) {
  console.log("network call");
  return data + 4;
}

function calculate(data) {
  console.log("heavy operation");
  return data + 2;
}

let memLookup = memoize(lookup);
console.log(memLookup(4)); //network call -> 8
console.log(memLookup(4)); //8
console.log(memLookup(6)); //network call -> 10
console.log(memLookup(6)); //10

let memCalculate = memoize(calculate);
console.log(memCalculate(4)); //heavy operation -> 6
console.log(memCalculate(4)); //6
console.log(memCalculate(6)); //heavy operation -> 8
console.log(memCalculate(6)); //8
Run Code Online (Sandbox Code Playgroud)