The thing is, the browser and the JS API you are using are directly wired. Where do you think the document and window come from? Why are they not in Node.JS? I think, it's easy to explain using Node.JS's VM module:
The VM module lets you run a script in a separated container, a sandbox, or however you'd like to call it. A similar functionality is exposed by JS interpreter libraries, like Google's V8, to lower-level programmers (in C++).
const vm = require('vm');
The initial global scope is empty. There is no JSON, there is no window, there is no document, there is no setTimeout, there is no nothing. In JS-terms, it would look like {}, not counting standard object methods and properties. So they add functions and objects with methods, implement them and, that way, can wire the render code directly to whatever you might write. A very simplistic example might look like the following snipped, with pseudo-code, entirely implemented in JS (normally it would happen in C++) for your convenience:
const sandbox = {
document: {
getElementById: function(id) {
// find element and return it as a new object
return {
// The following line is a setter: developer.mozilla.org/en-US/docs/Web/JavaScript/R…
set innerHTML(html) {
// repaint website
},
// various other properties
};
},
},
// various other functions and objects
};
const context = new vm.createContext(sandbox);
const script = new vm.Script(youJSFileHere);
// and execute some JS file you included in your HTML
script.runInContext(context);