JavaScript uses lexical scoping: The scope chain for a function is
determined solely by the location of the function definition in the source
code.

Evaling the function's source code is a clever solution, and probably the
only way to do this. With eval() you're creating a new function from source
code that is treated as if it were in the location of the eval() call.

Could you give a working example of how you'd actually use this? Maybe there
is a different way to approach the problem.

-Mike

> From: Allan Jardine
> 
> Hello all,
> 
> I'm running into a few problems with a plug-in I'm 
> developing. What I would like to do is to take a function 
> (which is in any old scope, global for example) and then 
> execute it in the scope of my plug-in. I rather thought I 
> would be able to do something like in my constructor:
> 
>       this.fnTest = fnGlobalTest;
> 
> This would take a reference of the global function and store 
> it in my object. It is just a reference being stored, so it 
> looks like it is then being executed in the original scope. 
> So I tried:
> 
>       this.fnTest = function() { fnGlobalTest.call( this ); };
> 
> Expecting that to work - it didn't. I can't access any of the 
> private functions. Indeed the only way I have managed to do 
> this is to:
> 
>       this.fnTest = eval( '('+ fnGlobalTest.toString()+')' );
> 
> Which is obviously far from ideal...
> 
> Does anyone have any suggestions for how I might do this?
> 
> Regards,
> Allan
> 

Reply via email to