javascript - 为什么我得到的闭包值为 "result"?

标签 javascript closures memoization

假设我有这段代码 ( fiddle ) 旨在内存模块:

var chat = {
 // Create this closure to contain the cached modules
 module: function() {
    // Internal module cache.
    var modules = {};
     console.log('in module:', name);  // <---------- "in return: result"     
    // Create a new module reference scaffold or load an
    // existing module.
    return function(name) {
      console.log('in return:', name); // <---------- "in return: derp"
      // If this module has already been created, return it.
      if (modules[name]) {
        return modules[name];
      }

      // Create a module and save it under this name
      return modules[name] = { Views: {} };
    };
  }()
};

chat.module("derp");

代码中根本没有提到“结果”这个短语。为什么它会在第一个控制台日志中返回该值?

此外,当 module: function() {} 声明中未指定任何参数时,返回函数如何获取 name 参数的值?

最佳答案

console.log('in module:', name);

您在声明name之前就记录了它。所以它使用 window.name相反。

关于javascript - 为什么我得到的闭包值为 "result"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165693/

相关文章:

javascript - 如何从 Native JSON 动态更新 jQuery Flot

Javascript 闭包和自动执行匿名函数

c# - 深入探讨关闭的实现

C# 内存具有任意数量参数的函数

haskell - 为什么这个 memoized 的 Pascal 三角递归没有预期的那么快?

python - 如何从 django 数据库中仅检索一次属性

javascript - pagemethods 未定义 - 我相信一切都应该没问题

javascript - Nodejs、expressjs - 如何提供延迟响应

rust - 从闭包返回闭包作为函数的返回值

javascript - 在 javascript 中替换 HTML5 视频 src 字符串不会替换视频