My function somehow doesn’t have access to its parent closure & is missing variables. How?

后端 未结 2 1870
既然无缘
既然无缘 2021-01-04 07:23

In my top-level function, I’m importing some dependencies using require.js. And they’re there, no problem. Within this function, I define a callback function and attempt to

相关标签:
2条回答
  • 2021-01-04 07:51

    I suspect that the function where you set the breakpoint contains a reference to Backbone, but not Vent or Foo.

    Closures are somewhat expensive on the JS runtime. It requires the engine wrap up the object in such a way that it keeps internal references to those variables so they can be resolved correctly at the time the function is executed. So for performance reasons, Chrome (and I suspect most other engines as well) has a tendency to optimize away any closure variables that aren't actually used when the script is compiled. This can lead to some confusing things when debugging, but it's to be expected.

    Consider the following example (Note x, y, and z are defined in the scope of the outer function, not in global scope):

    window.onload = function() {
      var x = 1, y = 2, z = 3;
      (function() {
        debugger;
        x++;
      })();
    }

    Alternate JSFiddle demonstration

    If you try to output x and y on the console when this script hits the debugger directive, this is what you'll see:

    Console Output

    And if you look at the Scope Variable panel you'll see:

    Scope Variables

    Why? because Chrome has determined that y and z are not used within the function so there's no need for the compiled code to keep a reference to the variable. If you add a reference to y within the script, then the compiler will keep a reference to it, and the name will no longer be undefined in the debugger.

    0 讨论(0)
  • 2021-01-04 07:52

    if you use eval() inside your closure Chrome will not use any of it's performance optimizations which means you can see the value of y

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