views:

232

answers:

1

How I can execute a JavaScript function/piece of code in a specific context which it would see as a global context? This is not the same as changing this (call/apply), this is more like changing 'window'.

Basically, if I have the following code:

(function() { x.value = 5; return value; })()

is there a way to make it work (return 5) without changing the code itself?

Also, executing code in the context of x (if possible) is my first idea, but maybe there is some other solution as well?

UPDATE:

Original problem: I am trying to test a bookmarklet using selenium. Bookmarklet assumes that it can do

window.SomeObject = {...}; SomeObject.doSomething();

I get the bookmarklet from the page and execute it using $selenium.get_eval, and in context of get_eval global object is some object of selenium itself, not the window. window.SomeObject still works because selenium context has window, but just SomeObject does not work.

I think I know another possible solution, but I would like to know if there is an answer to original question.

UPDATE 2 (solution):

Final solution (based on answer by geowa4):

x = {}; with(x) { return (function() { x.value = 5; return value; })(); }
+2  A: 

You can change your scope using the with keyword.

(function() { x.value = 5; with(x) { return value; })();

The with keyword scopes the block of code to the given object. So in this case, you will return 5.

geowa4
> Without changing the code itself?
Crescent Fresh
@crescentfresh: yeah, but that's impossible so i went with the closest option. a bit of a stab in the dark.
geowa4
I have added more details to the question. With is a very good idea, but will it work in outer scope? I'll check.
Andrey Shchekin
You rule. x = {}; with(x) { var result = (function() { x.value = 5; return value; })(); alert(result); } works perfectly!
Andrey Shchekin