On 09/12/2005 15:20, Evertjan. wrote:
PJ6 wrote on 09 dec 2005 in comp.lang.javascript:
[...] is it possible, with Javascript, to dynamically generate new
functions - that is, execute the text contents of a variable?
[snip]
a = "alert('yes')"
eval(a)
The eval function is an option, though if the OP really does want to
create functions, then the Function constructor would be more appropriate.
For example,
var myFunction = new Function('a', 'z', 'return a + z;');
or:
var myFunction = new Function('a,z', 'return a + z;');
is roughly the equivalent of:
function myFunction(a, z) {
return a + z;
}
The most significant difference between the first two and the third, is
that function declarations (the third) and expressions (shown below)
have their scope chain determined with respect to where they are
defined. Function objects created with the Function constructor only
ever have the global object in their scope chain. The following
demonstrates this:
function outer1(arg) {
return function() {
alert(arg);
};
}
function outer2(arg) {
return new Function('alert(arg);');
}
outer1('Hello world')(); /* Displays 'Hello world' */
outer2('Foo bar baz')(); /* Fatal error: arg is not defined */
The two outer* functions create and return function objects. The first
function will have the formal argument, arg, in its scope chain so it
may display its value. The second function does not and, because there
is no global variable named 'arg', an error will occur.
Mike
--
Michael Winter
Prefix subject with [News] before replying by e-mail.