0

Can help which one is best usage/implementaion from the below two type of javascript class creation (OOPs concept)?

way 1:

var MyClassName = function(){
  // private variables
  // private functions

  return {
    // public functions
    pubFunctionName1: function(){
    },
    pubFunctionName2: function(){
    }
  }
}

usage:

myClass = new MyClass();
myClass.pubFunctionName1();

way 2:

function MyClass(){
  //public variables and functions
  this.publicVariable = "";
  this.publicFunctionName3 = function(){
  }

  // private functions
  function privateFunctionName3(){
  }
}

usages:

var myClass = new MyClass();
myClass.publicFunctionName3();
sureshunivers
  • 1,753
  • 12
  • 27
  • 5
    There is never a **best** way to do anything. Only the most appropriate way for a very specific situation. – Philipp Jun 07 '13 at 08:12
  • 1
    In this case, there is no one best way. It would depend on the use case and what you are more comfortable with as both of them would give the same result. However I find the way 2 more comfortable as for me, it is more readable. But that would depend on the use case as well – Ankit Jun 07 '13 at 08:14
  • 4
    There's no such thing as a "class" in Javascript. Only objects. – deceze Jun 07 '13 at 08:18
  • Pholip and Ankit - Thanks for your replay. I am going to use way 2. Because, its easy for me to understand coding structure. – sureshunivers Jun 10 '13 at 05:29

2 Answers2

1

This often depends on your own taste and on how you want to use the class... But some months back I asked myself a similar question and found a useful description where different ways of defining classes in Javascript are explained . This could also be helpful to clarify things to you...

bertl
  • 2,084
  • 1
  • 15
  • 12
  • While this is a nice article, you should include it partly in your answer. Otherwise, if the link becomes unavailable *for whatever reason*, this answer will be useless. – Felix Kling Jun 07 '13 at 08:37
1

Checkout this book

It has specific chapter on constructors, very useful.

If in short: in both methods that you've proposed, you will lost connection with prototype, so you need to decide is it necessary for you.

One of another proposals could be something like:

/* self-inited constructor */
var Cat = function () {
  if (!(this instanceof Cat)) {
    return new Cat();
  }

  this.name = 'Tom';
};
Cat.prototype.meow = true;

var persian = new Cat();
var cheshire = Cat();

console.log(persian.name); // "Tom"
console.log(cheshire.name); // "Tom"
console.log(persian.meow); // true
console.log(cheshire.meow); // true
Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164
Kosmetika
  • 20,774
  • 37
  • 108
  • 172