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();
4
  • 5
    There is never a best way to do anything. Only the most appropriate way for a very specific situation.
    – Philipp
    Jun 7, 2013 at 8: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 7, 2013 at 8:14
  • 4
    There's no such thing as a "class" in Javascript. Only objects.
    – deceze
    Jun 7, 2013 at 8:18
  • Pholip and Ankit - Thanks for your replay. I am going to use way 2. Because, its easy for me to understand coding structure. Jun 10, 2013 at 5:29

2 Answers 2

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

1
  • 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. Jun 7, 2013 at 8: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

Not the answer you're looking for? Browse other questions tagged or ask your own question.