Extending Window To Create A Dynamic Scope Chain For Method Execution In JavaScript

Posted June 1, 2011 at 9:36 AM by Ben Nadel

Tags: Javascript / DHTML

Last week, I talked about using JavaScript's With keyword in order to create a dynamic scope chain that would form the context of a given function's execution. As a follow-up to that post, I wanted to try and accomplish the same kind of thing without having to rely on the With keyword. To do this, I used an approach that I've never thought of before - I extended the global scope (window object); that is, I used "window" as the prototype for my dynamic scope instance.


 
 
 

 
  
 
 
 

One of the fun things about using the with() block in my previous post was that you could use either locally-scoped values or allow the variable references to fall back to the global scope (window). In order to accomplish the same without the with() block, I simply created the "scope" as an extension of the window. In this approach, references can still fall back to the global object; however, this time, the underlying mechanism is the prototype chain, not the scope chain.

To see what I'm talking about, take a look at the following code. Notice that my "scope" variable is being created with Object.create() where "window" is the given prototype.

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <title>Extending Window To Create A Dynamic Scope Chain</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. In order to not
  • // use the "with" keyword, we want the scope instance
  • // to extend the global scope. This will allow us to
  • // override scope-based values; or, have them fall
  • // through to the global scope thanks to the prototype
  • // chain.
  • var scope = Object.create( window );
  •  
  • // Define our method. Notice that we are explicilty
  • // scoping our variables to the SCOPE.
  • var getFooMethod = function(){
  •  
  • // Return "foo";
  • return( scope.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.";
  •  
  • // Get closest-scoped foo value.
  • console.log( getFoo() );
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Store foo directly in the function scope.
  • getFoo.scope.foo = "Foo In Scope.";
  •  
  • // Get closest-scoped foo value.
  • console.log( getFoo() );
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Update the foo in global scope.
  • window.foo = "UPDATED Foo in Global.";
  •  
  • // Delete the foo from the scope.
  • delete( getFoo.scope.foo );
  •  
  • // Get closest-scoped foo value.
  • console.log( getFoo() );
  •  
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • Extending Window To Create A Dynamic Scope Chain
  • </h1>
  •  
  • </body>
  • </html>

As you can see, this time, scope is an extension of window. In order to wire this scope into the inner-function, however, we did have to replace unscoped references with explicitly scoped references (ie. "foo" became "scope.foo"). From an external standpoint, however, the logic remained exactly the same.

When we run the above code, we get the following console output:

Foo In Global.
Foo In Scope.
UPDATED Foo in Global.

As you can see, since scope extends window, we can selectively add and remove values anywhere we want in scope's prototype chain. This augmentation of the scope object effectively changes the runtime behavior of the getFoo() method.

As I said in my last post, I don't think any of this code has any practical use; I think the only possible value here is in the exploration of how JavaScript works. If nothing else, I think it was kind of fun to extend the actual window object.




Reader Comments

Mar 30, 2012 at 10:41 PM // reply »
1 Comments

This is lovely work, Ben. I'm using a similar thing during an implemention of a stack-based Forthish language in the browser. The justification is this:

> drawGraph

Should use the global stack for binding.

> splitOn standings drawGraph

Not only needs to invoke drawGraph as many times as standings splits down to, but needs to provide a different, filtered, stack to it each time.

Just wanted to let you know that somebody else was crazy enough to find a practical reason to use dynamic scoping in JS :D

c


Mar 31, 2012 at 9:26 AM // reply »
11,241 Comments

@Chris,

Ha ha, glad to see that someone out there appreciates my strange experimentation with getting JavaScript to do weird stuff :)


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 22, 2013 at 4:43 AM
How Do You Use The ColdFusion CFParam Tag?
'<cfparam>' or 'isDefined()and <cfset>' performs the same task.Is there any difference? ... read »
May 21, 2013 at 7:46 PM
Using Plupload For Drag & Drop File Uploads In ColdFusion
No luck. At least I have uncovered the cause, URLScan 3.1. Here is what I see in the IIS log when a file is over 30mb. 2013-05-21 23:29:05 10.105.45.128 GET /plupload/assets/jquery/jquery-1.8. ... read »
May 21, 2013 at 6:12 PM
Using Plupload For Drag & Drop File Uploads In ColdFusion
Ben, I did not see you after Pete Freitag's Lockdown session at cfObjective but he said that IIS sets file size limits at 30MB by default which just happened to be the threshold for file size when ... read »
May 21, 2013 at 11:51 AM
Ask Ben: Parsing Very Large XML Documents In ColdFusion
Looking at my first ever XML document that I have to parse and put into MS SQL 2000 with CF8. I get it to list the desired Field name, many times over, and have a long list of this field name displa ... read »
May 21, 2013 at 9:25 AM
Turning Off and On Identity Column in SQL Server
you are awesome..i am lucky to get this blog between such a garbage one....Thanks, Prashant ... read »
May 20, 2013 at 4:38 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Dana, Your confusion is well founded, since this is a very confusing features. In fact, it ONLY works if you use array notation. Meaning, that this: arrayToList( query[ "columnName" ] ) ... read »
May 20, 2013 at 4:34 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
I was thinking chicken and the egg, I wouldn't have expected it to work in the valuelist going in I guess. Maybe I just need a beer, long day :) ... read »
May 20, 2013 at 4:29 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Dana, That's if you're trying to reference a specific row. In this case, we're trying to reference the entire query column as one cohesive value. So, you are correct that if you wanted to output a ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools