Javascript - Closure, Scope
Javascript Closure Scope
HTML
<div id="results"></div>
<div class="animDiv">
<div id="anim1">A N I M A T I O N </div>
<div id="anim2">N O I T A M I N A</div>
</div>
<button id="test">Test function context</button>
CSS
body {
margin:10px;
}
.pass {
color:green;
}
.fail {
color:red;
text-decoration:line-through;
}
.animDiv{
height:270px;
width:350px;
border:black 1px solid;
}
JavaScript
// closure allows a function to access all the variables and functions that are in scope when the function itself is declared. A declared function can be called at any later time, even after the scope in which it was declared has gone away. All the variables and functions that were in scope when the function was declared become part of the closure.
function assert(value, desc) {
var res = $("#results");
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
res.append(li);
}
var outerValue = "ov";
var later;
function outerFunction() {
var innerValue = "iv";
function innerFunction(num) {
assert(outerValue, "outerValue is in scope");
assert(innerValue, "innerValue is in scope");
// function parameters are included in the closure of that function
assert(num, "num is in scope");
// all variables in an outer scope, even those after function declaration, are included
assert(somethingElse, "somethingElse is in scope");
// all functions in an outer scope, even those after function declaration, are included
assert(outerFunction2, "outerFunction2 is in scope");
}
later = innerFunction;
}
// within the same scope, variables not yet defined CANNOT be forward referenced
assert(!somethingElse, "somethingElse is not in scope");
var somethingElse = "se";
// within the same scope, functions not yet defined CAN be forward referenced
assert(outerFunction2, "outerFunction2 is in scope");
function outerFunction2(){}
// variables in an internal scope are inaccessible
assert(outerFunction.innerValue===undefined, "innerValue is not in scope");
// functions in an internal scope are inaccessible
assert(outerFunction.innerFunction===undefined, "innerFunction is not in scope");
outerFunction();
later(10);
// There is no closure object which is keeping all the things in scope.
// All the closure information is...