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.

License

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

 
GeneralReason for my vote of 5 Very nice alternative PinmemberSChristmas22-Nov-10 21:24 

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
Web04 | 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