JSFiddle - React, Tailwind, and code Playground
by kazabr
JavaScript
// Объекты, конструкторы, this
var calculator = {
a: 0,
b: 0,
readValues: function() {
this.a = +prompt('Введите значение a: ', 0);
this.b = +prompt('Введите значение b: ', 0);
return true;
},
sum: function() {
return this.a + this.b;
},
mul: function() {
return this.a * this.b;
}
};
/*
console.clear();
calculator.readValues();
console.log( calculator.sum() );
console.log( calculator.mul() );
*/
function Summator() {
this.a = 0;
this.b = 0;
this.sum = function() {
return this.a + this.b;
};
this.run = function() {
this.a = +prompt('Введите a: ', 0);
this.b = +prompt('Введите b: ', 0);
return this.sum();
};
}
/*
console.clear();
console.log( new Summator().run() );
*/
function Adder(startingValue) {
this.value = startingValue || 0;
this.addInput = function() {
this.value += +prompt('Добавить: ', 0);
};
this.showValue = function() {
console.log(this.value);
};
}
/*
var adder = new Adder(1);
adder.addInput();
adder.addInput();
adder.showValue();
*/
function Calculator() {
var operations = [[],[]];
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]) return NaN;
return methods[op](a, b);
/*
if(operator !== '+') {
for(var i=0; i<operations[0].length; i++) {
if(operator === operations[0][i]) {
return operations[1][i](a, b);
}
}
}
return a+b;
*/
};
this.addMethod = function(name, func) {
...