Load

Load a JavaScript string into a namespace. This could be used for loading an external file.

by rurtJH

HTML

<p>
The previous version of my <code>load</code> function used <code>eval</code>, but <a href="http://www.google.com/search?q=eval+is+evil">eval is evil</a>. A better option may be to use the <code>Function</code> constructor. Although Crockford even considers the <code>Function</code> constructor evil, I am sure he will prefer it over <code>eval</code>.
<p>
Now, on to the concern of global scoping. ECMAScript 5 has a new <em>"use strict";</em> directive. On feature of this directive is that it will prevent access to the global object. It is even used in lesser scopes, except when using a <code>Function</code> constructor. For that, one must add it to the constructor. This is shown in my <code>import_strict</code> function. This directive is not implemented by any browser currently, except for Firefox 4, but other browsers plan on implementing it. This will protect yourself in the future.
<pre id="my_script">
    this.say_hi = function() {
        alert("Hello, world!");
    }
</pre>

JavaScript

var my_script = document.getElementById("my_script").innerHTML;

function import(str) {
    return new (new Function(my_script));
}
function import_strict(str) {
    return new (new Function('"use strict";' + my_script));
}
var my_namespace = import(my_script);
my_namespace.say_hi();
say_hi(); //this is error