Javascript Object or new function for function handler -
i bit confused 1 of following right way create handler containing functions...an object function or new function itself? say, handler calculator functions...
calculatorhandler = new function(){ this.add = new function(a, b){ return + b; }; this.sub = new function(a, b){ return a-b; }; };
or
calculatorhandler = { this.add: function(a, b){ return + b; }, this.sub: function(a, b){ return a-b; } };
are there advantage/disadvantage of 1 on other?
if want have "basket" hold functions together, use object, there no need constructor function:
calculatorhandler = { add: function(a, b){ return + b; }, sub: function(a, b){ return a-b; } };
note how this
in example incorrect refer scope define calculatorhandler object in (probably global - window).
on other hand if want build calculator have data , operations on it, can use oop-like approach in 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 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);
Comments
Post a Comment