October 28, 2012
How to put a function inside an object and directly output the result
Question by Dan Myasnikov
Look, I ve got the following code to be executed and the result expected:
a = { a: function(){ return 'red'} }
so whenever I call
a.a #=> I would like to receive 'red' rather than 'function(){ return 'red'}
Any help appreciated
Answer by Starx
Simply do this
a = {
a: 'red'
};
But if having the result return function that important, we have to make sure the function get called and returned.
a = {
a: function() {
return 'red-by-function';
}() //This will ensure the function is called rather that returning the whole function
};
Demo of both cases