65.9K
CodeProject is changing. Read more.
Home

How to use Javascript as OOPS for beginner

starIconstarIconstarIconstarIconstarIcon

5.00/5 (5 votes)

Nov 22, 2010

CPOL
viewsIcon

18873

From what I understand of best practices in the JS world, one should not use the new keyword very often.For this example, I would suggest this as an alternate approach:Create a new script file arithmetic.jsvar Arithmetic = function(){ var obj = { add: function(a,b) { return a +...

From what I understand of best practices in the JS world, one should not use the new keyword very often. For this example, I would suggest this as an alternate approach: Create a new script file arithmetic.js
var Arithmetic = function(){
  var obj = {
    add: function(a,b) { return a + b; },
    multiply: function(a,b) { return a * b; }
  };
  return obj;
}();
This is known as a self-executing function, and it will create a closure. I won't go into how that works here, as there are several good articles around the web on the topic. This should then let you do this;
var resultAdd = Arithmetic.add(a,b);
var resultMul = Arithmetic.multiply(a,b);
There will still be cases where new is useful to you, but I think that it might surprise you how seldom it actually is.