Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 25, 2014 12:09
Show Gist options
  • Select an option

  • Save bennadel/9760529 to your computer and use it in GitHub Desktop.

Select an option

Save bennadel/9760529 to your computer and use it in GitHub Desktop.
Using JavaScript's With Keyword To Create A Dynamic Scope Chain For Method Execution
<!DOCTYPE html>
<html>
<head>
<title>Creating A Dynamic Scope Chain For Method Execution</title>
<script type="text/javascript">
// I return a function with a "scope" property that can be
// used to alter the runtime bindings of the functions.
var getFoo = (function(){
// Create the scope for our function.
var scope = {};
// Add the scope to the lookup-chain using the WITH
// keyword. This will add "scope" to the chain of
// memory spaces in which Javascript will try to
// locate property values.
with( scope ){
// Declare our closure within the WITH-based scope
// chaing.
var getFooMethod = function(){
// Return "foo";
return( foo );
};
}
// Add scope as a property to the method as well so
// that it can be access and mutated at runtime.
getFooMethod.scope = scope;
// Return the method.
return( getFooMethod );
})();
// -------------------------------------------------- //
// -------------------------------------------------- //
// -------------------------------------------------- //
// -------------------------------------------------- //
// Store foo in the global name space.
this.foo = "Foo In Global Scope.";
// Get closest-scoped foo value.
console.log( getFoo() );
// -------------------------------------------------- //
// -------------------------------------------------- //
// Store foo in the WITH-based function scope.
getFoo.scope.foo = "Foo In WITH-Based Scope.";
// Get closest-scoped foo value.
console.log( getFoo() );
// -------------------------------------------------- //
// -------------------------------------------------- //
// Update the foo in global scope.
window.foo = "UPDATED Foo in Global Scope.";
// Delete the foo from the WITH-based scope.
delete( getFoo.scope.foo );
// Get closest-scoped foo value.
console.log( getFoo() );
</script>
</head>
<body>
<h1>
Creating A Dynamic Scope Chain For Method Execution
</h1>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment