Undefined variable in close?

I have a function like this:

function foo(canvas) { canvas.mousedown(function(e) { console.log(canvas); //undefined }); } 

I call foo with a mouse click in a specific place on the page.

Why is canvas undefined?

+4
source share
4 answers

The problem was this:

 function foo(canvas) { canvas.mousedown(function(e) { console.log(canvas); //undefined //... for (var i in array) { var canvas = array[i].canvas; //... } }); } 

I don’t have time to investigate the exact cause. I assume that the compiler places the "var canvas" declaration at the beginning of the anonymous function, so that the undefined variable is displayed in the console. Otherwise, until you understand this.

+2
source

The debugger may not show variables in closure until they are used.

Consider this example where a variable is defined but never used:

 (function() { var x = 1; $(function () { debugger; // debugger stopped here, `x` is `undefined` in Chrome and IE but `1` in Firefox console.log("hi"); } })(); 

Instead of the string literal, the same code is printed except for the variable:

 (function() { var x = 1; $(function () { debugger; // debugger stopped here, all three browsers show `x` as `1` console.log(x); } })(); 
+10
source

Your own answer is correct as soon as you have submitted the entire code sample. You are faced with the Javascript quirk known as "variable lift". Your code is interpreted as:

 function foo(canvas) { canvas.mousedown(function(e) { var i, canvas; //variable declarations moved to top of function scope console.log(canvas); //undefined //... for (i in array) { canvas = array[i].canvas; //... } }); } 

Cm:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

+2
source

I just wanted to confirm that in chrome what Charlie said is correct. I needed to reference this variable before I could use it in closure when using the debugger instruction!

0
source

Source: https://habr.com/ru/post/1443089/


All Articles