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?

3
  • 1
    the second is not valid syntax Commented Sep 24, 2013 at 16:11
  • …and the first pattern should not be used Commented Sep 24, 2013 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. Commented Sep 24, 2013 at 18:02

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

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.