The following code sample (also at http://jsfiddle.net/MZwBS/)
var items = [];
items.push({
example: function() {
if(0 > 1) {
return 'true';
} else {
return 'false';
}
}
});
document.write(items[0].example);
produces
'function () { if (0 > 1) { return "true"; } else { return "false"; } }'
instead of
'false'
It seems like I've been able something like this with ExtJS. Can anyone tell me where I went wrong? I'd like to evaluate anonymous functions like this on-the-fly.
Function.toString() (which in this case is a string representation of the declaration) - NoName 2012-04-04 23:37
You want:
document.write(items[0].example());
When you skip the parentheses, you are saying, "Print this function." When you have them, you are saying, "Evaluate this function and print the result."
Do you mean to execute it?
document.write(items[0].example());
I've solved my issue by adding '()' after the anonymous function as shown below.
http://jsfiddle.net/MZwBS/7/
var items = [];
items.push({
example: function() {
if(0 > 1) {
return 'true';
} else {
return 'false';
}
}()
});
document.write(items[0].example);
This code block now produces the expected result of
'false'
()to execute a function - Joseph 2012-04-04 23:31