Reputation: 11
I am an ancient C programmer attempting to use HTML5, with some difficulty. I have defined a global function "MouseHandler" with variables local to that function including X and LastMsg.
A function MoveHandler is within MouseHandler, and placing a breakpoint at if (PostFunc)
I find the value of the local variables to be:
The code is:
var MouseHandler = function (canvas1, terraincvs1, PostFunc1)
{
// ...
var X, Y;
var LastMsg = "QQQ";
// ...
function MoveHandler ()
{
var ABCStr = Mouse.LastMsg;
var DEFStr = LastMsg;
var LocalX = X;
// ...
LastMsg = "Move " + X + ',' + Y;
if (PostFunc)
PostFunc ();
return { "LastMsg" : LastMsg }
}
cvs.addEventListener("mousedown", DownListener, false);
return { "DownListener" : DownListener, "UpListener" : UpListener, "MoveHandler" : MoveHandler,
"OffsetX" : OffsetX, "OffsetY" : OffsetY, "dX" : dX, "dY" : dY, "DownX" : DownX, "DownY" : DownY, "Down" : Down,
"LastMsg" : LastMsg }
}
// ...
var Mouse = new MouseHandler (canvas, HexCanvas, PostMouse);
It seems that LocalX is appropriately set to the value of "X" defined within the outer function MouseHandler, but LastMsg seems to be an (implicitly declared) local variable within the inner MoveHandler, rather than referring (as I expected) to the LastMsg defined within the outer function MouseHandler. Using the reference Mouse.LastMsg appears to refer to the value of the outer function's LastMsg, as might be expected.
Am I missing something obvious here? Can somebody direct me to an online reference for scope of variables for HTML5 that would clarify this issue for me?
Upvotes: 1
Views: 118
Reputation: 38223
These scoping issues are entirely related to JavaScript, and not so much HTML5.
JavaScript's variable scopes, although appearing to be identical to C-family block scopes, are actually function-level scopes. JavaScript will start with the innermost function and search outwards to "resolve" variables, so because you didn't have a definition of LastMsg
in your MoveHandler()
function, JavaScript went up the scope chain to the anonymous function that you defined inside of your MouseHandler
variable and there it found and resolved LastMsg
to the string QQQ
.
When you change the value of LastMsg
in the MoveHandler()
function, JavaScript simply discards the QQQ
values and creates a new string and assigns its reference to that variable because JavaScript strings are immutable.
Good links to read about this are:
JavaScript Scoping and Hoisting
What is the scope of variables in JavaScript?
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
Upvotes: 2