Search code examples
javascriptnamespacesresolutionidentifier

can I load a javascript file under a context other than 'window'?


I try to load some external .js files, and have some irresolvable namespace conflicts.

I had the idea of loading some of the files in their own context somehow, replacing the "this" from pointing at the window object to some custom namespace.

example:

first.js:

name = "first";

second.js:

name = "second";

It seems to me that this kind of trick can be very useful. Is it possible at all?

EDIT
seems that replacing "this" does not begin to solve the problem, as it is not the default context for identifier resolution in javascript. this is my test code:

var first = {};
var second = {};

(function(){name = "first";}).call(first);
(function(){name = "second";}).call(second);


document.write('name= '+name+' <br/>\n'); //prints "second"
document.write('first.name= '+first.name+' <br/>\n'); //prints "undefined"
document.write('second.name= '+second.name+' <br/>\n'); //prints "undefined

any ideas?

RESOLUTION
It is not possible. I ended up wiser than I was this morning, and I gave it up. I recommend these enlightening reading materials for anyone with a similar problem that might want to take a crack at it: http://jibbering.com/faq/notes/closures/
http://softwareas.com/cross-domain-communication-with-iframes


Solution

  • Even though this is an old question, this answer may still be relevant for some:

    When a js file is loaded it automatically gets the window's context. That is not possible to change. However, if you are trying to avoid conflicts between libraries that you are loading, and you don't have control over those libs, and they don't have a built-in "no-conflict" mechanism, then there is a nice trick - you can load those into a source-less iframe. This will make their context to be the window of the iframe, and you will still be able to access the iframe since there is no cross-domain issue here.

    You can see this library as an example for use of this technique.