Search code examples
javascriptjsonfunctionobject-literal

How to retrieve value from key:function the same way as key:value in JavaScript?


How can I retrieve foo2.x the same way as I retrieve foo1.x?

var foo1 = {x: 4};
var foo2 = {x: function(){return addOne(foo1.x);}}

function addOne(var1){return (var1 + 1);}

alert(foo1.x);
alert(foo2.x()); // needs parentheses, but argument is never needed

Solution

  • I assume that you want to store the result of that function in foo2.x, not the function itself.

    Try the following:

    function addOne(n) {
        return n + 1;
    }
    
    var
    foo1 = {
        x: 4
    },
    foo2 = {
        x: (function () {
            return addOne(foo1.x);
        }())
    };
    
    alert(foo1.x); // 4
    alert(foo2.x); // 5
    

    I've wrapped the function in foo2.x with parentheses, and put an extra pair of parens after it to execute it. So it's no longer a function, but the result of the function.