O
O
olya_0972018-02-15 02:19:07
JavaScript
olya_097, 2018-02-15 02:19:07

What does the function code in this.addMethod mean and what is it for?

function Calculator() {

  var methods = {
    "-": function(a, b) {
      return a - b;
    },
    "+": function(a, b) {
      return a + b;
    }
  };

  this.calculate = function(str) {

    var split = str.split(' '),
      a = +split[0],
      op = split[1],
      b = +split[2]

    if (!methods[op] || isNaN(a) || isNaN(b)) {
      return NaN;
    }

    return methods[op](a, b);
  }

  this.addMethod = function(name, func) {
    methods[name] = func;  //что значит?для чего он?и пример,если можно
  };
}

var calc = new Calculator;

calc.addMethod("*", function(a, b) {
  return a * b;
});
calc.addMethod("/", function(a, b) {
  return a / b;
});
calc.addMethod("**", function(a, b) {
  return Math.pow(a, b);
});

var result = calc.calculate("2 ** 3");
alert( result ); // 8

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nakree, 2018-02-15
@olya_097

In the methods object, a key is created called name (which we passed as an argument) and this key is assigned the value func (which we also passed as an argument) .
This line allows you to add new methods to the calculator.
For example multiplication:

calc.addMethod("*", function(a, b) {
  return a * b;
});

The first argument "*" is the name of the key, the second argument is an anonymous function that is assigned to the key.
As a result, the methods object will look like this:
methods = {
    "-": function(a, b) {
      return a - b;
    },
    "+": function(a, b) {
      return a + b;
    },
   "*": function(a, b) {
      return a * b;
  };

When one of the methods is called, the corresponding anonymous function will be executed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question