Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

How to use Javascript as OOPS for beginner

By , 22 Nov 2010
Rate this:
Please Sign up or sign in to vote.
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.


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

About the Author

Morten Nilsen

Norway Norway
No Biography provided

Comments and Discussions

Generalwhy not just rename obj to Arithmetic ? Pinmemberreed129-Nov-10 3:00 
GeneralReason for my vote of 5 Very nice alternative PinmemberSChristmas22-Nov-10 21:24 
Reason for my vote of 5
Very nice alternative
GeneralReason for my vote of 5 Good one Pinmvpthatraja22-Nov-10 16:04 
GeneralIf that does what I think it does, that is bloody brilliant!... Pinprotectoraspdotnetdev22-Nov-10 7:25 
GeneralYes . you are right if i am not wrong in jquery template the... Pinmembermaq_rohit22-Nov-10 5:32 
GeneralReason for my vote of 5 Thanks for great info sharing Pinmembermaq_rohit22-Nov-10 5:28 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 22 Nov 2010
Article Copyright 2010 by Morten Nilsen
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid