HTML and CSS Reference
In-Depth Information
When you run this code and click Div2 , the globalVar variable is in scope, the localVar
variable is in scope, but the insideDiv1Click variable isn't in scope. That variable lives only
within the Div1 onclick handler, so it's in scope only while that function runs. This example
raises an undefined exception when it tries to access the insideDiv1Click variable.
As a final example, update the code for Div3 and other functions as follows:
document.getElementById("Div3").onclick = function () {
var insideDiv3 = "Div3";
function AFunction() {
var x;
function BFunctionWithParam(p) {
In this code, the variable insideDiv3 is local to the onclick event handler for Div3 .
The onclick event handler has access to the globalVar and localVar variables just like
the other event handlers did. The event handler for Div3 also calls the AFunction and
BFunctionWithParam methods. The AFunction method attempts to access the insideDiv3
variable. Unfortunately, that variable lives only within the scope of the Div3 onclick handler.
The functions called from the Div3 click event function don't inherit or have access to the
local variables of the Div3 method. To access the local variables declared in the Div3 event
handler from another function, you need to pass them as parameters to those functions.
You can also see an illustration of passing a local variable as a parameter to another
function in the code. After the call to the AFunction method, the event handler calls the
BFunctionWithParam method. This function expects a single parameter named p . The onclick
event handler passes the value of the insideDiv3 variable to the method. Now, the p variable is
a local variable to the BFunctionWithParam method, so it can show the value of the insideDiv3
variable. This is the only way to make a local variable from one function accessible to another
function—by passing a parameter.
Next, the BFunctionWithParam method attempts to access the localVar variable. It assumes
it would have access, but it doesn't for the same reason the AFunction method doesn't have
access to the insideDiv3 variable. The localVar variable is accessible only to code within the
onload event handler in which it's declared. For functions outside that scope to have access to
it, you need to pass it as a parameter. One more thing to consider with respect to the lifetime
and scope of variables is hierarchy .
If you plan to use the values of globalVar or localVar variables in the onclick event han-
dlers for the various div elements, you must not declare any variables at the local level with
the same name. Locally scoped variables override higher-level scoped variables of the same
Search WWH ::

Custom Search