Answer the question
In order to leave comments, you need to log in
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
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;
});
methods = {
"-": function(a, b) {
return a - b;
},
"+": function(a, b) {
return a + b;
},
"*": function(a, b) {
return a * b;
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question