var res; function Calculator(){ while(true) { var question = prompt('введите выражение: ', ' '); if (question == null) { break; }else if(question == 0){ alert('введены некоректные данные'); } var methods = { '-': function(a, b){ return a - b; }, '+': function(a, b){ return a + b; }, '/': function(a, b){ return a / b; }, '*': function(a, b){ return a * b; }, '**': function(a, b){ return Math.pow(a, b); } }; res = question; 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; } alert(methods[op](+a, +b)); } } } var calc = new Calculator(); 

var result = calc.calculate (res); result ();

  • Does it even work for you, at least without a cycle? - Alexey Shimansky
  • yes, why doubts? - aleksei
  • tritely doesn’t work with copy-paste jsfiddle.net/6tz075fm - Alexey Shimansky
  • I am new to programming, explain what copy - paste is - aleksei
  • And then programming? Copy-paste is usually called so - Alexey Shimansky

1 answer 1

I do not know how much code you have, for copying it and inserting it for yourself and trying it, nothing works.

In general, the cycle needs to be inserted not in the class, but already outside it. And somehow this is a cycle of control just in case.

I did a little in my own way, as a result there is a method that is called in the hasInput() loop. If it returns false , then everything ends; if true , it counts what has been entered. Data is stored in the class field. For if there is a class, then what's the point of what is put inside the class to put in an external variable?

You can still modify for everyone. But the main idea comes down rather to the fact that the cycle should be in this case in the outer part, and in the class there should be some flag that can interrupt it.

 function Calculator() { this.expression = null; this.hasInput = function() { return this.init(); }; this.init = function() { this.expression = prompt('введите выражение: ', ' '); if (this.expression == null) { return false; } else if (this.expression == 0) { alert('введены некоректные данные'); } return true; }; this.methods = { '-': function(a, b) { return a - b; }, '+': function(a, b) { return a + b; }, '/': function(a, b) { return a / b; }, '*': function(a, b) { return a * b; }, '**': function(a, b) { return Math.pow(a, b); } }; this.calculate = function() { var split = this.expression.split(' '), a = +split[0], op = split[1], b = +split[2]; if (!this.methods[op] || isNaN(a) || isNaN(b)) { return NaN; } alert(this.methods[op](+a, +b)); } } var calc = new Calculator(); while (calc.hasInput()) { calc.calculate(); }