javascript - Very weird behavior when using "var" keyword in an ajax request -
i've been worrying while , can't realize what's happening. explanation in code comments. there 2 versions of application, 1 of them throws weird results , second 1 expected work.
var id = "test1"; $.post("http://fiddle.jshell.net/echo/json/", {"data": "data"}, function(a) { alert(id); // throw undefined var id = "test2"; alert(id); // throw "test2" expected });
$.post("http://fiddle.jshell.net/echo/json/", {"data": "data"}, function(a) { alert(id); // throw "test1" expected id = "test2"; alert(id); // throw "test2" expected });
i'm not sure if has ajax call, or anonymous function, way discovered better keep there. explain missing? why behave differently when ommit var
keyword? can try out here on jsfiddle
cool, discovered hoisting
. mdn explains anyone:
because variable declarations (and declarations in general) processed before code executed, declaring variable anywhere in code equivalent declaring @ top. means variable can appear used before it's declared. behavior called "hoisting", appears variable declaration moved top of function or global code.
code sample mdn link below:
bla = 2 var bla; // ... // implicitly understood as: var bla; bla = 2;
you can see how result in "weird behaviour":
alert(testid); var testid = 2;
is equivalent to:
var testid; alert(testid); testid = 2;
which brings me final bit of knowledge can impart, always declare variables @ top of code blocks "weird behaviour" coded programs (and never throws off again):
function somefunction() { var firstvar, secondvar, thirdvar; //rest of code statements here }
https://developer.mozilla.org/en-us/docs/web/javascript/reference/statements/var#var_hoisting
Comments
Post a Comment