Как установить локальную переменную в классе - PullRequest
1 голос
/ 03 марта 2020
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()
        }
      });
    });
  }
}

В приведенном выше коде я хочу удалить параметры в моих методах сложения, вычитания, вычисления и деления и установить свойство переменной в классе, чтобы я мог напрямую вызывать сохраненные значения в методах и сделать операцию. Как это можно сделать?

Ответы [ 4 ]

2 голосов
/ 03 марта 2020

Правильное имя для локальных переменных класса - это поля :

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

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

Также имя функции класса - это методы

Вместе методы и поля члены

1 голос
/ 03 марта 2020

Вы можете установить значения в конструкторе

var prompt = require('prompt');

prompt.start();

class Calculator {
  /**
   * @param {number} firstValue get the first value
   *  @param {number} secondValue get the second value
   */
  constructor() {
    console.log(`Enter the numbers and the operation index you want to perform: 
        1) Addition 
        2) Substraction 
        3) Multiplication 
        4) Division`);

    this.firstValue = 0;
    this.secondValue = 0;

    this.calculate();
  }

  addition() {
    return this.firstValue + this.secondValue;
  }

  subtraction() {
    return this.firstValue - this.secondValue;
  }

  multiplication() {
    return this.firstValue * this.secondValue;
  }

  division() {
    if (this.secondValue != 0) {
      return this.firstValue / this.secondValue;
    }
    return 'Cannot perform division by 0';
  }

  calculate() {
    prompt.get(['firstValue', 'secondValue'], (error, values) => {
      if (error) {
        throw new Error(error);
      }

      this.firstValue = Number(values.firstValue);
      this.secondValue = Number(values.secondValue);

      prompt.get(['choice'], (responseError, response) => {
        if (responseError) {
          throw new Error(responseError);
        }

        let result = 0;

        switch (Number(response.choice)) {
          case 1:
            result = this.addition();
            break;
          case 2:
            result = this.subtraction();
            break;
          case 3:
            result = this.multiplication();
            break;
          case 4:
            result = this.division();
            break;
          default:
            console.log('>>>>>  Please select valid operation');
            break;
        }

        console.log('>>>>>  result : ', result);

        prompt.get(['optionSelected'], (responseError, response) => {
          if (responseError) {
            throw new Error(responseError);
          }

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

new Calculator();
0 голосов
/ 03 марта 2020

Классы не являются функциями, имеющими локальную или глобальную область. Классы имеют поля , и вы можете использовать свои поля следующим образом:

class Calculator {
    constructor() { 
         this.field = 10
    } 
    print() { 
        console.log(this.field)
     }
 };
0 голосов
/ 03 марта 2020

Вы можете установить локальную переменную в классе, используя ключевое слово this. Просто установите его, используя this.myVar = myValue в любом месте вашего класса. Переменная не должна быть определена до того, как вы ее назначите, и ее можно получить в любом месте вашего класса таким же образом. Обратите внимание, что он также доступен (и доступен для записи) за пределами класса.

...