javascript - Define a class Calculator that can satisfy the following code. var cal = new Calculator(); cal.add(3, 5);// 8 cal.add([3, 5]);// 8 -
define class calculator can satisfy following code.
var cal = new calculator(); cal.add(3, 5);// 8 cal.add([3, 5]);// 8
how code?
function calculator(){ this.p1=p1; this.p2=p2; this.add =function(){ return this.p1+this.p2; } } var cal = new calculator(); console.log(cal.add(3, 5));
it cannot work
you implement parameter methode add
.
function calculator(){ this.add = function (p1, p2) { return p1 + p2; } } var cal = new calculator(); console.log(cal.add(3, 5));
or use method input, stack , method addition.
function calculator() { this.stack = []; } calculator.prototype.input = function (value) { this.stack.push(value); } calculator.prototype.add = function () { var value = this.stack.pop() + this.stack.pop(); this.stack.push(value); return value; } var cal = new calculator; cal.input(3); cal.input(5); console.log(cal.add());
Comments
Post a Comment