DR01D
DR01D

Reputation: 1365

How do I store the result of a function in the same object?

Question: I created an object that contained 2 named values. One is a function and the other is the value produced by the function. My problem is that I can't figure out the syntax for the second named value. How do I reference it? I've looked everywhere but I can't find a similar example object that I can learn from. Thanks so much!

var answer = {
    addNumbers: function(a, b, c) {
        return a + b + c;
    },
    result: answer.addNumbers;  //I'm not sure what the syntax is for this line.
};

Upvotes: 0

Views: 56

Answers (3)

Slai
Slai

Reputation: 22876

The last result of the function can also be stored in the function object:

function addNumbers(a, b, c) {
    addNumbers.result = a + b + c
    return addNumbers.result
}

addNumbers(1,2,3)

console.log(addNumbers.result)

Otherwise, it's possible by executing a function that accepts another function and returns the object:

var result = (function(f, a, b, c) { 
  return {
    addNumbers: f,
    result: f(a, b, c)
  }
})(function(a, b, c) { return a + b + c }, 1, 2, 3)

console.log(result)

Upvotes: 1

Psi
Psi

Reputation: 6793

I don't really get what you want to do, but if you want to store the result everytime the function gets executed, you might want to do something like this:

var answer = {
    addNumbers: function(a, b, c) {
        this.result = a + b + c;
        return this.result;
    },

    result:0
};

I think I'll explain the JSON a little bit:

In general, you just list a number of properties. Here, we specify addNumbers and result and assign values to them.

The value for addNumbers is a Function-object (thus callable), the value for result is a Number-object (0 in this case).

You now can execute addNumbers by calling it like answer.addNumbers(1,2,3). When this happens, everything between { and } of the function body gets executed, including the new assignment of this.result.

There's more stuff to this topic, especially how this is resolved in several cases, but that would exceed the scope of this answer.

Upvotes: 1

JCOC611
JCOC611

Reputation: 19739

Would the following be acceptable to you?

var addNumbers = function(a, b, c) {
    return a + b + c;
}
var answer = {
    addNumbers: addNumbers,
    result: addNumbers(...)
};

Alternatively:

var answer = {
    addNumbers: function(a, b, c) {
        return a + b + c;
    }
};
answer.result = answer.addNumbers(...);

Upvotes: 1

Related Questions