Do closures keep the whole execution context alive?

后端 未结 2 1735
青春惊慌失措
青春惊慌失措 2021-01-05 18:00

I understand that closures keep the execution context alive by saving a reference to the executed function.

I\'m wondering whether the whole context is saved or only

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 18:37

    If you put an eval statement inside the closure, you can access the closure-scope variables by their name even if they weren't used inside the closure. EDIT: as apsillers points out in the comments, browsers could probably optimise away unused variables EXCEPT if there's an eval statement inside the closure, in which case everything must be kept. It doesn't mean they do, but it's possible.

    var ctx;
    var outer_function = function (code) {
        var dummy = 'not required for output';
        var inner_function = function () {
            return { output: eval(code) };
        }
        return inner_function;
    };
    
    ctx = outer_function('dummy');
    ctx(); // { output: 'not required for output'}
    

提交回复
热议问题