You can specify the parameters calcthat the object returns to calculate something with two numbers, or just create an object calcwith functions that calculate something. Your requirement calc.multiply(10,20)for the second solution:
var calc = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
},
multiply: function(a, b) {
return a * b;
},
divide: function(a, b) {
if (b != 0) return a / b
alert('division by zero');
return false;
}
};
Otherwise, for use calc(10,20).multiply(), this will be the construction of the closure that you already have, but with parameters instead of two local constants:
function calc(a, b) {
return {
add: function() {
return a + b;
},
subtract: function() {
return a - b;
},
multiply: function() {
return a * b;
},
divide: function() {
if (b != 0) return a / b
alert('division by zero');
return false;
}
};
}
Bergi source
share