1

I'm trying to get better understanding of JavaScript and what it's under the hood. I've read different guides on the Object-Oriented Paradigm based on Prototypes used by JavaScript but I really can't understand how this kind of paradigm is different with the regular one with classes used for example in Java.

It seems to me to act in the same way, but only with a weird and tricky syntax. Am I wrong? What is the difference between them?

Could you please give me a concrete example in which the JS paradigm could be successfully used and in which the regular OOP paradigm is not well suited?

  • Closure and lambda expressions are kind of hard to make in traditional OOP -- but you are seeking a opinionated discussion which is not a good format for this site. – Soren May 02 '16 at 14:14
  • Am I? I'm just asking what is the difference between Prototype based and Class based paradigm. – Pasquale Muscettola May 02 '16 at 14:16
  • 2
    Try to read this question: http://stackoverflow.com/questions/816071/prototype-based-vs-class-based-inheritance – Soren May 02 '16 at 14:20

1 Answers1

1

The difference is that in Java, C++, python, php and other languages that support OOP you usually have two different language elements - one is Class which serves as a metadata and then we create new objects based on the class definitions; object this way is the second element of the language.

In JavaScript there is no Class element, there is only object. And we can create an object and then use it as a prototype to create other objects, for example:

var animal = {
  "name": "Bim",
  "age": 5
};

// now we can use the animal object iself, for example pass it to some function
// that shows object name
function showName(obj) {
  alert(obj.name);
}
showName(animal);

// but we also can use it as a prototype to create new objects
var dog = Object.create(animal);
dog.bark = function() {
  alert(this.name + ": bark! bark!");
}
dog.name = 'Pluto';
dog.bark();

There are ways to emulate the OOP with classes as it works in other languages and that is what you are probably referring to in act in the same way, but only with a weird and tricky syntax.

Actually is not necessary to have classes and it depends on your habits and application design. It is possible to work with just objects especially if you prefer composition to inheritance.

Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54