Created
March 21, 2012 22:53
-
-
Save lennym/2153939 to your computer and use it in GitHub Desktop.
Example of object and function based variable scope.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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