I stumbled on this post by Dustin on using the with keyword to sandbox some modules:
http://dustindiaz.com/sandboxing-javascript
The actual code snippet is:
(function () {
with (this) {
{{ender}}
{{library}}
}
}).call({})
Can somebody please explain what he is doing in a better way? I’m not quite able to follow the advantage of using the with(this) here, and what {{ender}} and {{library}} mean. He compares this approach to using iframes (which I understand), but I am not able to quite get what he is trying to do here.
He is causing all variables (and functions) declared inside that function to be inside the context of
this, i.e. the context of the wrapping function.Normally if you create variable using
varinside a function it’s local to that function, and that’s good. But what if you don’t? In that case by usingwithall variables that would otherwise be global are instead in the context of the with (in this case the context isthisof the function.)