In my previous blog post, I used the eval() function to "extend" the local scope with individual context variables; in the following demo, however, I'm going to use the "with" keyword to actually add the "this" context onto the scope chain of the function execution:
As you can see, I am taking the original source and wrapping it inside of a "with-block". I am then passing the "this" context reference to the "with" statement which will add it [this] to the function's scope chain. Then, as the function executes, any non-local, unqualified variables referenced within the source code will be searched for within the "this" scope.
Inside of the with-block, I am wrapping the original source code within a self-executing function block. This is not necessary and is something that I am doing purely for emotional reasons. By packaging the source code up in such a way, I feel like I am completely separating the execution of the source code from the scope-chain-extension afforded by the "with" statement. Again, not necessary, but emotionally satisfying.
When we run the above code, we get the following console output:
Molly, you in danger, girl!
As you can see, the context object applied to the sayHello() function by way of the apply() method was successfully used as one of the scopes in the unqualified-variable scope chain. Pretty awesome! I've never been a huge fan of the "with" keyword; but, a huge thanks to Pedro - this is a much more elegant solution than the one I had yesterday.
Want to use code from this post? Check out the license.