0

how to make a object which has a simple method to add two digits in javascript

 calc.sum(1,2);

here calc is an object with sum method which takes two parameters and return the value as 3.

1
  • please explain it also Commented Jun 10, 2015 at 9:35

4 Answers 4

1
var calc = { sum : function(a, b) {
    return a+b;
   } 
};

Now call it using:

var test = calc.sum(1,2);
Sign up to request clarification or add additional context in comments.

Comments

1

the basic concept is

var calc = {};
calc.sum = function(a, b) {
    return a+b;
}

As well you can do:

var createCalc = (function(){
   var sum = function(a, b) {
       return a+b;
   };
   return {
       sum : sum
   } 
});
var cal = createCalc();

or

function Calc() {
  this.sum = function(a, b) {
           return a+b;
  };
}

var calc = new Calc( );

I always recommend this github with patterns. http://shichuan.github.io/javascript-patterns/#object-creation-patterns

Comments

0

You can simply define the object like so:

var calc = 
    { 
        sum : function(a,b){ return a + b; }
    };

Comments

0
var calc={
   sum:function(1,b){
       return a+b;
   }
}

Now you can use this method

 var value = calc.sum(1,3)

//value = 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.