1

Is both defining a function and using it in a literal notation for an object possible?

var solution1 = {
  compute: function() {
    var toplam = 0;
    for (var i = 1; i < 1000; i++) {
      if (i % 3 == 0 || i % 5 == 0)
        toplam += i;
    }
    return toplam;
  },
  answer: solution1.compute() //This is the problem.
}
1
  • yeah but it didnt work, Ammar's work great. Thanks both of you for answers Commented Aug 13, 2015 at 22:33

1 Answer 1

4

At definition time, solution1 will be undefined.

Use a getter instead like

var solution1 = {
  compute: function() {
    var toplam = 0;
    for (var i = 1; i < 1000; i++) {
      if (i % 3 == 0 || i % 5 == 0)
        toplam += i;
    }

    return toplam;
  },
  get answer() {
    return this.compute();
  }

};

console.log(solution1.answer);

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, as i moved the logic to classes, this also saved me from defining solution[i].answer = solution[i].compute() everytime, just what i needed!
I wonder if you could simply give that function a name or just reference it as "compute", ie, no "this"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.