Using function results in "function source code" and not evaluated function value?

Go To StackoverFlow.com

3

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.

2012-04-04 23:27
by johnwp
what you did was print the function. you didn't execute it. you have to add () to execute a function - Joseph 2012-04-04 23:31
The result you get is actually quite cool, didn't know it was possible - d_inevitable 2012-04-04 23:34
Some browsers implement a somewhat useful Function.toString() (which in this case is a string representation of the declaration) - NoName 2012-04-04 23:37
I have updated the title with what is being observed. I believe this is accurate for this question; if the answers below are not correct, consider reanalyzing the situation and posting a new question - NoName 2012-04-04 23:40
@d_inevitable: It comes in handy when writing short quines ; - Kendall Frey 2012-04-05 00:08


2

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."

2012-04-04 23:28
by Kendall Frey
Thanks for your reply. Sorry, I should have been more clear. document.write is just an example. I actually want to pass items to another function. In the way I want to implement this, there may also be several anonymous functions in items. Do I need to somehow loop through each item in items to execute before I send it to a different function - johnwp 2012-04-04 23:38
It sounds like you want to execute the function after passing it to another function, and use its value there. You should be able to use the same code as above within the called function - Kendall Frey 2012-04-05 00:07


3

Do you mean to execute it?

document.write(items[0].example());​
2012-04-04 23:29
by meder omuraliev


0

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'
2012-04-08 03:22
by johnwp
Ads