【问题标题】:Why do I get the value "result" for this closure?为什么我会得到这个关闭的值“结果”?
【发布时间】:2023-03-11 22:29:01
【问题描述】:

假设我有这段代码 (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参数的值?

【问题讨论】:

    标签: javascript closures memoization


    【解决方案1】:
    … = function() {
        // …
        console.log('in module:', name);  // <---------- "in return: result"     
        return function(name) {…};
    }();
    

    你看,在立即执行的匿名函数表达式的范围内,没有变量“name”。因此,将使用全局变量 window.name - 在您的情况下,它的值似乎是 "result"(jsfiddle 目标 iframe 的名称) - 尝试使用 unwrapped page,它将记录一个空字符串。

    【讨论】:

    • 是的,在 jsfiddle 中,名称是 result。但在新文档中,它将是一个空字符串。
    • 是的,result 是 jsfiddle 应用的目标 iframe
    【解决方案2】:

    仅供参考……本例中的“result”是JsFiddle中右下窗口(div/iframe)的名称(或者说是ID)…… p>

    正如@Rocket 和@Bergi 已经说过的......你得到了“window.name”

    【讨论】:

    • 是的,从他们的回答中得知。
    【解决方案3】:
    console.log('in module:', name);
    

    您在声明之前正在记录name。所以它改用window.name

    【讨论】:

    • 好的,那么回答我的第二个问题,如果没有提供,返回函数如何确定要使用的值?
    • @Jason:因为return function(name)。您正在创建一个返回函数的函数,然后立即调用它。 chat.module 实际上被设置为 function(name)(返回的函数)。
    • Ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh。多么棘手! return 之前的部分有点像一个秘密的小世界,它的存在是为了帮助 return 函数。
    • 我一直在使用闭包,我现在才弄清楚这一点。让我感到羞耻
    • @Jason:每天学习新东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2021-07-10
    • 2021-12-22
    相关资源
    最近更新 更多