Вопрос

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
Это было полезно?

Решение 2

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.

Другие советы

It seems you want a getter function:

var foo1 = {x: 4},
    foo2 = {get x() { return foo1.x + 1; }};

foo2.x; // 5
foo1.x = 0;
foo2.x; // 1

foo2.x is a function, so you need to add parenthesis

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top