0

I have this test code to practice closures in JS but I'm getting not so expected result at the end

<script>
    var curryLog, logHello, logStayinAlive, logGoodbye;

    curryLog=function(arg_text){
        var log_it=function() {console.log(arg_text);};
        return log_it;
    };
    logHello=curryLog("hello");
    logStayinAlive=curryLog("stayin alive!");
    logGoodbye=curryLog("goodbye");

    // this creates no reference to the execution context,
    // and therefore the execution context object can be
    // immediately purged by the JS garbage collector
    curryLog("Fred");
    logHello();
    logStayinAlive();
    logGoodbye();
    logHello();

    // destroy reference to "hello" execution context
    delete window.logHello;
    //destroy reference to "stayin alive"
    delete window.logStayinAlive;

    logGoodbye();
    logStayinAlive(); // undefined - execution context destroyed, but still getting
                      // "stayin alive!" ??
</script>

from this I expect the console to log out : "hello", "stayin alive!", "goodbye", "hello", "goodbye" and finally undefined because I just deleted it? but for some reason after delete window.logStayinAlive I'm still getting "staying alive" and not "undefined". Why it is so?

lychee
  • 1,771
  • 3
  • 21
  • 31
  • within curryLog anonymous function is not assign to windows object so delete operator has not effect. – Blauharley May 16 '15 at 16:48
  • Since you defined it with `var` `logStayinAlive` is a local variable. It is not part of window. So the only way to delete it is to set it to null or undefined. – Tesseract May 16 '15 at 17:04

0 Answers0