使用构造函数时变量不持久

时间:2018-10-04 00:48:49

标签: javascript constructor this

所以我正在使用这样的构造函数

const RPNCalculator = function () {
  let methods = {
  numberList: [],
  calc: 0,   
  push(num) {
   this.numberList.push(num);
  },
  plus() {
    for (let i = 0; i <= this.numberList.length; i++) {
      console.log('before:' + this.calc);
      this.calc = this.calc + this.numberList[i];
    }
    console.log('after:' + this.calc);
    this.numberList = [];  
  }
};
  return methods;
}

const rpnCalculatorInstance = new RPNCalculator; 

第一个console.log可以正确打印并添加元素,但是第二个console.log可以打印NaN。我之前在Object.create中使用了这种模式,但是由于某种原因,使用构造函数时this.calc变量不持久。 任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:0)

您可以使用reduce总结一个数组https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

在下面运行代码段

class RpnCalculator{
 constructor(){
  this.numberList = [];
  this.push = (num) => { this.numberList = [...this.numberList, num ]}
  this.sum = () => {return this.numberList.reduce(( a, c) => a + c, 0);}
  }
}

const rpnCalculator = new RpnCalculator();
rpnCalculator.push(1)
rpnCalculator.push(2)
rpnCalculator.push(3)
console.log(rpnCalculator.sum());

答案 1 :(得分:-1)

显然,对于数据集,我得到了数组中的最后一项是未定义的元素。我通过使用

对其进行了修复
    if (typeof (this.numberList[i]) === 'number') {
      console.log('before:' + this.calc);
      this.calc = this.calc + this.numberList[i];
    }