I'm a bit confused as to how scope is seen by/related to inner objects. I understand that scope defines how variables are enclosed/seen and that context referes to the creation and binding of this to an object, and that inner objects and functions have access to the global object; however, I don't understand how (or if) scope relates to objects.
- How does scoping work under the hood?
- Are the only ways to access an external variable in an object via (a) binding the
this
that contains the external variable to the object or (b) adding that variable to the global object? Or, do objects have references to external scopes using javascript scoping?
I'm trying to set up a NodeJS web server and want to define a local variable which can be accessed by all other inner objects that are constructed in the entry (index) file. I tried to do this with var x = 10;
in the entry file; yet, when I try to access the variable from an object instantiated later on in the code, there is no way to access that variable. I instantiated an object using the new
operator, then called a method in that object that logs x
to the console, but I get an "x is not defined" error. When debugging in chrome, I can't find x
defined anywhere. I see the global context, which appears to just be the global object, I see the local context, which appears to be the instantiated object, yet I see no reference to the context that instantiated the object. I can place the variable on the global object and then it can be referenced, but I don't want to fall into the bad habit of placing everything on the global object.
Top-Level (file called startup.js and is called using node startup.js
):
var express = require('express');
var web = express();
var Controller = require('./classes/Controller');
var x = 10;
var controller = new Controller(props);
web.post('/addEntry', function(req, res){
controller.createEntry(req.body, (error, status) =>{
if (error) {
res.send('Error: ' + error);
console.log(error);
}
res.send("Success:" + status);
});
});
web.listen(3000);
Controller file:
class Controller {
constructor()
createEntry(entry, callback) {
console.log(x);
return callback(entry);
}
}
module.exports = Controller;
- I would like to be able to reference
x
from an inner scope in an established pattern that is considered good practice. If this isn't possible using variables in higher-level contexts than the methods in instantiated objects, I would really appreciate it if you could suggest an alternative (preferably that isn't attaching to the global object). Thank you for your time and help and please let me know if and how I can improve the post!