javascript - 如何在类中设置局部变量

标签 javascript node.js class

class Calculator {
  constructor() {
    console.log(`Enter the numbers and the operation index you want to perform: 
        1) Addition 
        2) Substraction 
        3) Multiplication 
        4) Division`);

    this.calculate();
  }

  /** 
   * @param {number} firstValue get the first value
   *  @param {number} secondValue get the second value 
   */
  addition(firstValue, secondValue) {
    return firstValue + secondValue;
  }

  /**
   * @param {number} firstValue get the first value
   *  @param {number} secondValue get the second value 
   */
  subtraction(firstValue, secondValue) {
    return firstValue - secondValue;
  }

  /** 
   *  @param {number} firstValue get the first value 
   *  @param {number} secondValue get the second value 
   */
  multiplication(firstValue, secondValue) {
    return firstValue * secondValue;
  }

  /** 
   *  @param {number} firstValue get the first value 
   *  @param {number} secondValue get the second value 
  */
  division(firstValue, secondValue) {
    if (secondValue != 0) {
      return firstValue / secondValue;
    }
    return 'Cannot perform division by 0';
  }

  calculate() {
    prompt.get(propertiesPrompt, (error, values) => {
      if (error) {
        throw new Error(error);
      }

      console.log(operationResult[values.operation](values.valueOne, values.valueTwo));
      prompt.get(choiceResponse, (responseError, response) => {
        if (responseError) {
          throw new Error(responseError);
        }

        if (response.optionSelected.toLowerCase() == 'y') {
          this.calculate()
        }
      });
    });
  }
}

在上面的代码中,我想删除加减乘除方法中的参数,并想在类中设置一个变量属性,以便我可以直接调用方法中存储的值并进行操作。怎么可能做到这一点?

最佳答案

局部类变量的正确名称是字段:

class Calculator {
  constructor() {
    this.field = 10
  }

  show() {
    console.log(this.field)
  }
}

类的函数名称也是一个方法

方法和字段一起是成员

关于javascript - 如何在类中设置局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60501974/

相关文章:

javascript - 自调用函数 jQuery

c++ - 我必须在类的头文件中提及私有(private)方法吗?

java - 带有选择的基本加法和减法

javascript - 在 extjs 中使用 Ext.get() 获取类

javascript - 如何设置具有相同ID的多个div相对于它们在DOM中的位置的边距高度

javascript - 如何在 Ember.js 中循环排序数组 Controller ?

javascript - 如何不覆盖node.js中的文件

node.js - 类型错误 : Object #<ServerResponse> has no method 'redirect'

node.js - 获取给定一场比赛的所有关联记录

class - 可变方法 X.this 无法使用 D 中的不可变对象(immutable对象)错误进行调用