Click here to Skip to main content
15,867,141 members
Articles / Programming Languages / Javascript
Alternative
Tip/Trick

How to use Javascript as OOPS for beginner

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
22 Nov 2010CPOL 16.4K   5   6
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)


Written By
Norway Norway
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalwhy not just rename obj to Arithmetic ? Pin
reed129-Nov-10 3:00
reed129-Nov-10 3:00 
GeneralReason for my vote of 5 Very nice alternative Pin
Sandesh M Patil22-Nov-10 21:24
Sandesh M Patil22-Nov-10 21:24 
GeneralReason for my vote of 5 Good one Pin
thatraja22-Nov-10 16:04
professionalthatraja22-Nov-10 16:04 
GeneralIf that does what I think it does, that is bloody brilliant!... Pin
AspDotNetDev22-Nov-10 7:25
protectorAspDotNetDev22-Nov-10 7:25 
GeneralYes . you are right if i am not wrong in jquery template the... Pin
maq_rohit22-Nov-10 5:32
professionalmaq_rohit22-Nov-10 5:32 
GeneralReason for my vote of 5 Thanks for great info sharing Pin
maq_rohit22-Nov-10 5:28
professionalmaq_rohit22-Nov-10 5:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.