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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!