i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Sandboxing JavaScript

Today I fired off a tweet that in some developers eyes may have been controversial

But to the point, the task at hand I was trying to solve was to bundle a set of core modules built by Ender along side my own library (that uses Ender), and not populate the global space.

Moreover, I'm not talking about sandbox natives, but something more along the lines of what Dean Edwards wrote in 2006 using iframes — except I don't want to use iframes. They're clunky, slow, and most definitely an unprofessional way of shipping a library

The collisional problem

The moment I require Ender in my library, it conflicts with your (the developer) version of Ender — and/or more importantly (and perhaps the most common use-case) your version of jQuery. The two different $ functions will collide.

The poor man's way of doing this, of course, would ask the developer to kindly call jQuery.noConflict(). (That's pretty un-pro). Likewise if my library calls ender.noConflict() it removes the developers instance of Ender (if one exists).

Enter, context pattern

One specific pattern you'll see in nearly every module (or micro-library for wording-sake) in Ender is the notion of exporting your public interfaces to an outer-scope. See Klass, Valentine, domReady, Query for references.

That pattern looks like this

(function (context) {
  
  context.public = fn
  
}(this))

Of course, this is seemingly no different than explicitly setting window.public = fn since in this scenario this === window. So what gives? Well...

Enter, sandboxing

Providing the fact that your library is using the context pattern (and not setting public interfaces on window), sandboxing becomes easy

(function () {

  with (this) {
    {{ender}}
    {{library}}
  }

}).call({})

In this case {{ender}} represents a custom build of Ender, and {{library}} represents your library's use of that build — all while not exposing the public Ender $ interface. Therefore your library has effectively sandboxed its modules! Pretty cool, eh?

On a final note, don't believe the hype on what is indeed a useful language feature.

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.