Aditya Jain
Aditya Jain

Reputation: 1095

Javascript Object or new function for function handler

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?

Upvotes: 0

Views: 223

Answers (1)

Tibos
Tibos

Reputation: 27823

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);

Upvotes: 2

Related Questions