有关对象/调用函数的问题

时间:2014-10-11 23:24:48

标签: javascript function object invocation

所以我解决了这个问题,因为我正在通过项目euler进行一个课程,现在我需要使用对象进行操作,而且我一直在搜索google,但我希望能找到一些关于我可能出错的建议。试图存储变量以供以后使用,mianly fiboSeq似乎永远不可用。我只是把这个功能叫错了吗?任何建议或朝着正确方向学习的观点都会很棒。

function solution(){
  return {
    fibo: function(limit, prev, curr){
      var fiboSeq = [];
      for (curr = curr; curr < limit; curr = prev + curr){
        prev = curr - prev;
        fiboSeq.push(curr);
      }
      return fiboSeq;
    },

    filterEvens: function(index){
      var evens = [];
      fiboSeq.forEach(function(value, index){
        if (value % 2 === 0){
          evens.push(value);
        }
      });
      return evens;
    },

    sum: function(evens){
      sumEvens = 0;
      evens.forEach(function(value, index){
        sumEvens += sumEvens
      });
      return sumEvens;
    }
  }
}

var seqF = solution().fibo(100, 1, 2);
var evenF =  solution().filterEvens(seqF);
var victoryD = solution().sum(evenF);
console.log(victoryD);

谢谢!

2 个答案:

答案 0 :(得分:0)

fiboSeq位于fibo()的本地范围内。要从其他函数访问它,您应该将其作为参数传递,或者在返回的对象之外定义它。

function solution(){
  var fiboSeq = [];
  return {
    fibo: function(limit, prev, curr){
      for (curr = curr; curr < limit; curr = prev + curr){
        prev = curr - prev;
        fiboSeq.push(curr);
      }
      return fiboSeq;
    },
    // ...
  }  

答案 1 :(得分:0)

查看以下代码:

function solution(){
  this.fiboSeq = this.evens = [];
  this.fibo = function(limit, prev, curr){
    for(var c=curr,l=limit,p=prev; c<l; c=p+c){
      p = c-p; this.fiboSeq.push(c);
    }
    return this;
  }
  this.filterEvens = function(){
    var fs = this.fiboSeq;
    for(var i=0,l=fs.length; i<l; i++){
      if(fs[i] % 2 === 0){
        this.evens.push(fs[i]);
      }
    }
    return this.evens;
  }
}
var sol = new solution;
var evenF = sol.fibo(100, 1, 2).filterEvens(); 
var eFl = evenF.length;