Why do I get the value “result” for this closure?

2019-01-27 02:49发布

问题:

Let's say I have this code (fiddle) intended to memoize modules:

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");

Nowhere in the code is the phrase "result" even mentioned. Why would it return that value in the first console log?

Also, how does the return function get the value for the name parameter when none is specified in the module: function() {} declaration?

回答1:

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

You are logging name before you ever declare it. So it's using window.name instead.



回答2:

… = function() {
    // …
    console.log('in module:', name);  // <---------- "in return: result"     
    return function(name) {…};
}();

You see, in the scope of that immediately-executed anonymous function expression, there is no variable "name". Therefore, the global variable window.name will be used - it's value seems to be "result" in your case (the jsfiddle target iframe's name) - try the unwrapped page, it will log an empty string.



回答3:

Just for reference... "result" in this example, is the name (or better say the ID) of the lower right window (div/iframe) in JsFiddle...

So as @Rocket & @Bergi already says... you are getting the "window.name"