Reputation: 766
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.
Upvotes: 3
Views: 121
Reputation: 766
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'
Upvotes: 0
Reputation: 186672
Do you mean to execute it?
document.write(items[0].example());
Upvotes: 3
Reputation: 44374
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."
Upvotes: 2