In this brief lesson on Javascript scoping, consider the following:
function someFunction() {
var foo = 'bar';
}
someFunction();
// foo is not accessible
The variable foo
exists only within the scope of the function someFunction()
; once the function executes, foo
ceases to exist.
To address this issue, you can assign foo
to the "global object," such as "window":
function someFunction() {
window.foo = 'bar';
}
someFunction();
// now foo exists!
However, resorting to using the global object for all variables can quickly lead to a cluttered codebase (programming languages utilize scopes for a reason: avoiding the global space simplifies code management).
Instead, focus on reconciling where draw
is created and utilized in your code, aiming to consolidate them or have the creating function return draw
, among other strategies.