0

I am a bit confused as which one of the following is the right way to create a handler containing functions...An object with function or a new function itself? Say, a handler for calculator functions...

CalculatorHandler = new function(){
    this.add = new function(a, b){
          return a + b;
    };
    this.sub = new function(a, b){
          return a-b;
    };
};

Or

CalculatorHandler = {
    this.add: function(a, b){
          return a + b;
    },
    this.sub: function(a, b){
          return a-b;
    }
};

Are there any advantage/disadvantage of one over the other?

Aditya Jain
  • 1,077
  • 1
  • 12
  • 25
  • 1
    the second is not valid syntax – Luca Rainone Sep 24 '13 at 16:11
  • …and the first pattern [should not be used](http://stackoverflow.com/a/10406585/1048572) – Bergi Sep 24 '13 at 16:26
  • @chumkiu I also thought that at first, but now I think that it is valid (though it won't work properly here). All that the `new` keyword wants is a function to invoke, and it's got that here. The resulting value of course will be a plain object and not a function. – Pointy Sep 24 '13 at 18:02

1 Answers1

2

If you just want to have a "basket" to hold your functions together, simply use an object, there is no need for a constructor function:

CalculatorHandler = {
    add: function(a, b){
          return a + b;
    },
    sub: function(a, b){
          return a-b;
    }
};

Note how the this in your example is incorrect as it will refer to the scope you define the CalculatorHandler object in (probably global - window).

On the other hand if you want to build a calculator to have some data and do operations on it, then you can use the OOP-like approach in your first example.

CalculatorHandler = function() {
  this.total=0;

  this.add = function(a) {
    this.total += a;
  };

  this.sub = function(a) {
    this.total -= a;
  };
}

var calc = new CalculatorHandler();
calc.add(4);
calc.sub(3);

And a better solution, based on prototipal inheritance:

CalculatorHandler = function() {
  this.total=0;
}

CalculatorHandler.prototype.add = function(num) {
  this.total += num;
}

CalculatorHandler.prototype.sub = function(num) {
  this.total -= num;
};

var calc = new CalculatorHandler();
calc.add(4);
calc.sub(3);
Tibos
  • 27,507
  • 4
  • 50
  • 64