Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

How to use Javascript as OOPS for beginner

5.00/5 (5 votes)
22 Nov 2010CPOL 18K  
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)