[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/calculator-constructor [Back]  [Original]

Create new Calculator
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Create new Calculator

    importance: 5

    Create a constructor function Calculator that creates objects with 3 methods:

    • read() prompts for two values and saves them as object properties with names a and b respectively.
    • sum() returns the sum of these properties.
    • mul() returns the multiplication product of these properties.

    For instance:

    let calculator = new Calculator();
    calculator.read();
    
    alert( "Sum=" + calculator.sum() );
    alert( "Mul=" + calculator.mul() );

    Run the demo

    Open a sandbox with tests.

    solution
    function Calculator() {
    
      this.read = function() {
        this.a = +prompt('a?', 0);
        this.b = +prompt('b?', 0);
      };
    
      this.sum = function() {
        return this.a + this.b;
      };
    
      this.mul = function() {
        return this.a * this.b;
      };
    }
    
    let calculator = new Calculator();
    calculator.read();
    
    alert( "Sum=" + calculator.sum() );
    alert( "Mul=" + calculator.mul() );

    Open the solution with tests in a sandbox.


    Web Proxy Viewer  |  New URL  |  Original Page