Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 451
Amir Arad Avatar asked Nov 08 '10 08:11

Amir Arad


1 Answers

One idea I've had for doing it without needing modifications to your external JavaScript file is getting the contents of the JavaScript file in an AJAXy way (up to you how you do that) and then put it all in a function using the new Function(code) way, then initialise that with new:

surrogateWindow = new new Function(jsCode)();

Then surrogateWindow is the this of that code. I think that that idea should work.

like image 192
Chris Morgan Avatar answered Nov 09 '22 22:11

Chris Morgan