Function usage results in "function source code" and function value is not evaluated?

Following code example (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

'false'

      

It seems that with ExtJS I was able to do something similar. Can anyone tell me where I went wrong? I'd like to evaluate anonymous functions like this on the fly.

+3


source to share


3 answers


Do you want to:

document.write(items[0].example());

      



When you omit the parentheses, you say "Print this function". When you have them, you say, "Appreciate this feature and print the result."

+2


source


Do you want to fulfill it?



document.write(items[0].example());​

      

+3


source


I solved the problem 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 gives the expected result

'false'

      

0


source







All Articles