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 »
10,743 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
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 21, 2012 at 1:58 AM
Updated: Converting A ColdFusion Query To CSV Using QueryToCSV()
Hi Ben, why do you need to have so many double quotes when adding the field and field name to the row data? ----------------------------------------- <cfset LOCAL.RowData[ LOCAL.ColumnIndex ] = ... read »
AXL
May 21, 2012 at 1:24 AM
URL Rewriting And ColdFusion's WriteToBrowser Image Functionality (CFFileServlet)
@Mounir, Open your lower case URL Rewrite rule and add the following condition. Condition input: {REQUEST_URI} Check if input string: Does Not Match the Pattern Pattern: ^/CFFileServlet/_cf_ca ... read »
May 20, 2012 at 4:28 AM
Understanding The Complex And Circular Relationships Between Objects In JavaScript
@Will Vaughn I tried your javascript example but got this error:- foo.print is not a function ... read »
May 19, 2012 at 5:37 AM
A Graphical Explanation Of Javascript Closures In A jQuery Context
Thanks for this article, but I fear you missed an important point. If variables in the outer context change, these changes affect the inner anonymous functions as well. That means: if you change the ... read »
May 18, 2012 at 3:39 PM
Parsing CSV Data With An Input Stream And A Finite State Machine
Can you use file upload button with this? and read live? or does the file have to already be on the server saved? ... read »
May 18, 2012 at 1:06 AM
VIRGO (Aug. 23-Sept. 22): Dead On The Money!
A friend of mine and I were arguing about astrology and she told me that he believes in astrology. She hasn't provided me with any evidence that the belief makes any sense to me. She she been telling ... read »
May 17, 2012 at 11:32 PM
Using ColdFusion to Handle 404 Errors (Page Not Found) On Development Server
Very easy the configuration. I read a lot pages and I can't find the solution. I open the administrator and change this Administrator/server settings/Error Handlers/Missing Template Handler and p ... read »
May 17, 2012 at 3:13 PM
LOCAL Variables Scope Conflicts With ColdFusion Query of Queries
I never cease to be amazed that almost EVERY random CF issue I come across lands me on your site. Thank you for documenting your findings for the world. ... read »