Skip to content

Instantly share code, notes, and snippets.

@lennym
Created March 21, 2012 22:53
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 lennym/2153939 to your computer and use it in GitHub Desktop.
Save lennym/2153939 to your computer and use it in GitHub Desktop.
Example of object and function based variable scope.
/** Example of Object based scope **/
ExampleObject = {
setVariable: function () {
this.value = 'foo';
},
getVariable: function () {
// this.value is accessible from here because it was declared as a property of "this"
return this.value;
}
}
ExampleObject.setVariable();
ExampleObject.getVariable(); // => 'foo'
ExampleObject.value // => 'foo' - can also be accessed as a property of ExampleObject
/** Example of function based scope **/
function () {
var aVariable;
function set () {
aVariable = 'bar';
}
function get () {
return aVariable;
}
set();
get(); // => 'bar' - aVariable can be accessed from both functions because it was declared in a shared parent scope
aVariable; // => 'bar'
}
set(); // => Error - set is undefined or not a function - set does not exist here, because it was not declared in the current scope or a parent scope.
aVariable; // => undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment