定义函数并以对象的文字符号使用它是否可能?

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.
}

最佳答案

在定义时,solution1将为undefined

使用getter代替



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);

10-06 00:11