0

I was reading about OOP in JS, but confused between traditional OOP versus object literal. And I also found in github many great JS projects weren't written the 'OOP way'. They leverage the object leteral pattern like revealing pattern and singletons. I came from Java, now I'm consufed between below pattern, on when to use them.

OOP :

function cook(){
this.vege = 'something';
}

var Cook = new cook();
console.log(Cook.vege = 'something else')

Versus object literal way :

var cook = {

vege:"something"

}
cook.vege = "something else"
Maria Jane
  • 2,353
  • 6
  • 23
  • 39

2 Answers2

1

Frequently, you'll only need an object literal. However, if you're wanting to create multiple object instances using the same patterns, you should use a constructor function to avoid repeating yourself. This is also important if you want to share things, like methods, across instances:

function Cook(name) {
  this.name = name;
  this.vege = 'something';
}

Cook.prototype = {
  cookSomething: function () { ... },
  doDishes: function () { ... }
};

Now you can do:

var fred = new Cook('Fred');
var lisa = new Cook('Lisa');

...and they'll all have a cookSomething and doDishes method.

Jacob
  • 77,566
  • 24
  • 149
  • 228
0

Let's say, there are 100 objects created for a particular student:

var Student = function (name) {
  this.name = name;
  this.greet = function () {
    console.log("My name is " + this.name);
  };
};

var praveen = new Student("Praveen Kumar");
var hello = new Student("Hello, World!");
var jeff = new Student("Jeff Atwood");

praveen.greet();
hello.greet();
jeff.greet();

But what if, suddenly I want to add another function like greet() function to:

console.log("Hola! This is " + this.name);

The now the "class" comes in handy.

var Student = function (name) {
  this.name = name;
  this.greet = function () {
    console.log("My name is " + this.name);
  };
};

var praveen = new Student("Praveen Kumar");
var hello = new Student("Hello, World!");
var jeff = new Student("Jeff Atwood");

Student.prototype.sayHola = function () {
  console.log("Hola! This is " + this.name);
};

praveen.sayHola();
hello.sayHola();
jeff.sayHola();

It is easy to add in one single prototype than keep adding for all the objects. This adds the function to all the objects.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252