Define all external JavaScript in a pre-existing namespace

Viewed 470

I am fully aware of the dangers of eval and such, so please don't waste your time commenting on how these hacks are hacks.

Say I'm using a third-party JavaScript library, but I'd like all of it's code to be defined within a particular namespace... that I also don't control. For example:

<script src="http://example.com/library.js>
<!-- library.js contains:
     var x = 0;
     function foo() {}
-->

I'd like to be able to define x and foo in the context of, say, namespace Bar, instead of the global context (window).

Assuming Bar is defined, but in another external js file that I don't control, I have tried some hacks, for example:

<script>
var externalCode = $.ajax("http://example.com/library.js");
eval.call(Bar, externalCode);
// and also tried:  
(function(str){ eval(str); }).call(Bar, externalCode);
</script>

But I am not able to access Bar.x nor invoke Bar.foo().

Basically, I want to achieve the results I would get if I pasted the contents of library.js inside my Bar namespace, a la:

var Bar = {
    x: 0,
    foo: function() {}
  }

However, I am trying to do this when I also lack control over the Bar namespace. Hence I can't "copy and paste." Another related example is how we can "punch in" new methods into pre-existing class definitions in Ruby.

Lastly, my specific use case is that I'm trying to "inject" everything from p5.js into the Opal namespace.

2 Answers
Related