0

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

8
  • x without var becomes a global var when it is first used (here: x = xmlDoc.getElementsByTagName("CD");) - but where is next() used? Commented Jan 29, 2017 at 17:01
  • Where is next() even called? It's defined but not used so that may be why it doesn't give an error. Commented Jan 29, 2017 at 17:02
  • I don't fully grasp this concept. x comes from var xmlDoc = xml.responseXML; so xmlDoc is a local variable. when displayCD(0) finished executing, wouldn't xmlDoc (and XmlHttpRequest object) get destroyed? How then does x remain? Not sure how all this works. Commented Jan 29, 2017 at 17:04
  • @Bert, Hi, I missed a line when copy-pasting. I edited the code. The original link is w3schools.com/js/tryit.asp?filename=tryjs_ajax_app_navigate Commented Jan 29, 2017 at 17:07
  • 1
    x doesn't "remember" how it got its value. Simplified example: if a is local, b is global and var a = 1; b = a; then the value of b will always be 1 (unless specifically changed) even if a doesn't exist anymore. Commented Jan 29, 2017 at 17:09

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Beat me for a minute :( here a quick explanation about scopes which I think would make everything clear w3schools.com/js/js_scope.asp
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.