To clarify this - I do not expect eval to work on anything but string.
That said, my hope is that Javascript has a way of getting a reference
to a function "by name" so I can avoid the need of marshalling and
using eval.
Please don' t top-post, now everyone has to scroll down to the bottom
to see what you are talking about, then come back to the top to see the
reply.
All functions declared in a global scope are properties of the global
object. JavaScript provides two methods for getting references to
object properties - dot notation and square bracket notation.
To reference a global function using square bracket notation:
function foo() {...}
window['foo']();
To use a varaible:
var bar = 'foo';
window[bar](); // calls foo();
You use dot notation where the string supplied is the name of the
property you want to access (e.g. window.foo() in the above) and use
use square bracket notation when you want the supplied parameter to be
evaluated - 'foo' evaluates to foo, as does bar.
One final note, the window object may not be available in every user
agent that runs your script, so you might want to use the global object
instead (they are synonymous in browsers):
// Declare in global scope:
var _global = this;
Now use _global wherever you would have used window.
How do you load a function using appendChild? Or do you load the
script element containing the function using appendChild?
call is a method of the Function object, so not really a good name for
a variable (personal preference). To do what you want here (without
eval):
var _global = this;
var fnName = 'fn1';
var call = _global[fnName];
call is now a reference to the (presumably) function object fn1, and
call() should execute it.
You never 'pass an object' - you always 'pass' a reference to an
object.
A fundamental principle of JavaScript is that where a variable is
assigned a primitive value, then:
var a = 5;
var b = a;
Both a and b now have a value of 5, it is effectively copied to b.
Modifying the value of a will not have any effect on the value of b.
When a variable is assigned a value that is a reference to an object,
then:
var objA = new Object();
var objB = objA;
The value of objA is a *reference* to the object, so the reference is
copied to the value of objB. objA and objB now reference the same
object. Therefore modifying (the object referenced by) objA will also
modify (the object referenced by) objB - it is the same object.
So wherever the value of a variable is assigned to some other variable
( var b = a) its value is always copied, just that sometimes it is a
primitive value and other times it is a reference to an object. You
may hear the saying 'primitives are passed by value, objects are passed
by reference' - don't believe it, for me it completely obfuscated what
is really happening.
I hope I did!
If not, please let me know.