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

后端 未结 3 1230
迷失自我
迷失自我 2020-12-20 02:42

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

var chat = {
 // Create this closure to contain the cached modules
 module: function() {
           


        
相关标签:
3条回答
  • 2020-12-20 03:08
    console.log('in module:', name);
    

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

    0 讨论(0)
  • 2020-12-20 03:12
    … = 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.

    0 讨论(0)
  • 2020-12-20 03:19

    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"

    0 讨论(0)
提交回复
热议问题