0

I have an HTML-file and a JS-file. Here they are:

HTML:

<head>
    <meta charset = "UTF-8">
    <title>Quiz Maker for Moodle - EGE Exam</title>
    <link rel = "stylesheet" type = "text/css" href = "style.css">
    <script src = "script.js"></script>
    <script> doc = document; </script>
</head>

JS:

var doc;    
function printSomething() {
    doc.writeln("HELLO");

}

You see what I'm doing here: I create a global variable to store my document there and then I use is the function. If I don't do it, and write document.writeln("HELLO"), the function doesn't work.

However, I assume this is a bad practice. If I'm right, is there a correct way of making my document available to all functions in all JS-files I might want to attach later on?

alekscooper
  • 795
  • 1
  • 7
  • 19
  • The built-in document is a global variable – IAmDranged Dec 17 '16 at 06:53
  • The use of global variables are frowned upon because of the possibility of code that's elsewhere that could be using variables with the same name. If you're concerned you can [namespace](http://stackoverflow.com/a/881556/2813224) your script. – zer00ne Dec 17 '16 at 06:58
  • Side note: write/writeln are interesting methods. I'd recommend reading about them https://developer.mozilla.org/en-US/docs/Web/API/Document/write to clearly understand what you should expect. – Alexei Levenkov Dec 17 '16 at 07:00
  • @IAmDranged Hm.. Then why doesn't my function in the separate file work if I do not pass the document as a parameter? – alekscooper Dec 17 '16 at 17:21
  • Is there any error printed out to the console? If so what is it? Could you provide the complete code? – IAmDranged Dec 17 '16 at 20:23

0 Answers0