Reputation:
I came across a sample HTML/Javascript code
<!DOCTYPE html>
<html>
<body>
<div id='showCD'></div><br>
<input type="button" onclick="previous()" value="<<">
<input type="button" onclick="next()" value=">>">
<script>
var i = 0;
displayCD(i);
function displayCD(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("CD");
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
function next() {
if (i < x.length-1) { // why does x here not raise an error? it came from nowhere.
i++;
displayCD(i);
}
}
</script>
</body>
</html>
The only question I had is why is it okay to use x
in function next(){}
when it is defined in myFunction(xml, i){}
?
When the page first loads, displayCD(0) is executed. So the only theory I could come up with is x
stays in memory because it is a global variable (it does not use var
.)
Please correct me if I am wrong.
Thanks
Upvotes: 0
Views: 76
Reputation: 1888
You're wondering why encapsulation isn't occuring? Because functions aren't treated as objects. Variables in functions are always created on their parents scope. But you can create encapsulated scope using javascript objects:
var a = {};
a.z = "a";
console.log(z); //undefined error
Or you can wrap your functions like this to encapsulate them:
(function(){
var x = "1";
})();
console.log(x); //undefined
Or better yet, create a scope:
var myObject = {};
myObject.myMethod = function(){
var g = "2";
}
console.log(g); //undefined
https://jsfiddle.net/1a3tkzpz/1/
Upvotes: 0
Reputation: 1709
When the function "myFunction" executes then, the variables without var is attached to window object. In console, you can see it by trying window.x and it will show some output.
Then, you can access x from any function or outside the function.
If you try to access x before executing "myFunction", then it will display error.
Upvotes: 1