1

I have been seeing this behaviour for a long time, had a few minutes of downtime and thought I'd ask this question.

I have a codepen done here:

http://codepen.io/ShashankaNataraj/pen/eZEYRZ?editors=1010

Its a block of JS code, nothing fancy, problem is there is weird behaviour I don't understand:

angular.module('helloWorld',[])
.controller('HelloWorldController',function($scope){
  $scope.sample = 'abc';
  $scope.clickHandler = function(){


    /**
    * When this debugger hits, try to type in $scope or $scope.sample in the console,
    * the console will fail to resolve $scope too with the error:
    * VM646:1 Uncaught ReferenceError: $scope is not defined(…)
    */
    debugger;
    /**
    * As soon as the below console.log statement is uncommented, when the debugger above hits,
    * if one types in $scope or $scope.sample in the console, it gets resolved!
    *
    */
    //console.log($scope.sample);
  }

});

Like I said in the comments above, if the console.log statement is uncommented, the browsers console is able to resolve $scope and $scope.sample just fine! What gives?!

Initially I was under the assumption that this was due to some closure related behaviour, but weirdly, this seems to be the case with non angular code as well

http://codepen.io/ShashankaNataraj/pen/MyvWGe?editors=1010

shashanka n
  • 2,568
  • 1
  • 14
  • 21
  • @dandavis how does that explain the console resolving the scope variable when it is referenced atleast once in the click handler? – shashanka n Mar 29 '16 at 04:08
  • 1
    Check out this SO answer: http://stackoverflow.com/a/28431346/69817 – Erik Ahlswede Mar 29 '16 at 04:10
  • 1
    For the second code pen linked, I am able to reproduce the problem in chrome, but NOT in firefox. Perhaps this is a browser-specific bug? (edit: nevermind the above comment from Erik explains it, I guess as of writing, Firefox isn't implementing this v8 optimization?) – Scott Mar 29 '16 at 04:10
  • nevermind, it didn't explain it. deleted. – dandavis Mar 29 '16 at 04:12
  • i was not able to recreate the "eval" behavior described by accepted answer : http://codepen.io/anon/pen/grxOjq?editors=1010, but i think the answer still makes sense. – dandavis Mar 29 '16 at 04:14
  • @Scott Thanks for that link, the accepted answer does explain this behaviour but the problem is that I like to hit breakpoints and check which variables are accessible and then write my code in my console and copy paste into my IDE. There is a lot of sphagetti code in my project that a few `java` devs in my team wrote before I came here. – shashanka n Mar 29 '16 at 04:19
  • I usually mention my variables by name if I plan to use them in the console. Something like `debugger;$scope;currentUser;productId`. Unfortunately that doesn't help if you don't know which variables you'll want to look at. – Matt Zeunert Mar 29 '16 at 17:21

0 Answers0