Created
July 23, 2013 20:29
-
-
Save tibbon/6065875 to your computer and use it in GitHub Desktop.
Javascript 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
function calculateHeight(startPoint, endPoint) { | |
// This function has access to startPoint and endPoint. Nothing else does. | |
return Math.abs(startPoint - endPoint) | |
} | |
function calculateWidth(startWidth, endWidth) { | |
// Function arguments act as local. ie. startWidth here is local | |
// This function has access to startWidth and endWidth. Nothing else does. | |
// Does this have access to a, b, x, y? No | |
// Does this have access to q? No | |
// Does this have access to z? YES. It is global | |
// Does this have access to marker? YES. It is global. | |
alert(z); | |
return Math.abs(startWidth - endWidth); | |
} | |
function calculateArea(x, y, a, b){ | |
// This function has access to x, y, a, b | |
var q = 100; // This is local to just this function | |
z = 200; // this is global. Don't do this! | |
alert(marker); // This has access to marker | |
return calculateHeight(x, y) + calculateWidth(a, b); | |
} | |
// If there's a Javascript library that uses "marker" it can access this as well. | |
// Anything declared outside of a function is global to everything. | |
var marker = "green"; // This is accessible in calculateArea. Its GLOBAL | |
// Same thing as doing marker = "green"; | |
calculateArea(100, 200, 300, 400); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment