Skip to content

Instantly share code, notes, and snippets.

@slickplaid
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slickplaid/2852cca04551d952087a to your computer and use it in GitHub Desktop.
Save slickplaid/2852cca04551d952087a to your computer and use it in GitHub Desktop.
Question about Scope in Javascript
var module2 = require('./module2');
// will return the same exact output from console.log as inside the module
module2.function1();
module2.function2();
// If you want to get around this, you will want to pass the variables, or set them inside the proper scope
var module3 = require('./module3');
// We can pass publicVariable into module3 if we need to.
module3(module2.publicVariable);
var insideScopeModule2 = true;
var PublicVariableWeGiveAccessToThroughExports = true;
var function1 = function(input1) {
var variableInsideFunction1 = true;
console.log(insideScopeModule2); // will return true always because of the scope it is executing in.
};
var function2 = function(input2) {
console.log(variableInsideFunction1); // will always return undefined unless we somehow pass it to this function
};
exports.function1 = function1;
exports.function2 = function2;
exports.publicVariable = PublicVariableWeGiveAccessToThroughExports;
// exports is equivalent to
// module.exports = { function1: function1, function2: function2 };
// http://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js
var privateVariableToModule3 = true;
var privateFunction = function() {
// This function is never exported, therefore will never be able to be accessed outside of this module.
// It does have access to everything inside of here, though.
var onlyInsideofPrivateFunction = true;
};
var publicFunction = function(input) {
// has access to both the private and public inside of here
// We can access the input variable though, and use anything passed into the function:
var publicVariableFromModule2 = input.publicVariable;
// we can use that input however we want.
};
module.exports = publicFunction;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment