14

Background

I am a developer with a background history of approximately 9 years in both Java and C#.

In those languages, Classes and taxonomic classification and inherent to the object paradigm.

And so, when ECMA6 came out, I was very happy to see classes in the language... and I started using them everywhere.

Problem

Turns out that using classes in JavaScript is a trap.

If you use them, you will go to your grave never knowing how miserable you are.

And you will never really understand JavaScript. You will think you do, but you don't.

Questions

So clearly, after watching this full conference, I realized I don't know JavaScript.

All my life I have been formatted with the OOP with classes paradigm, and now I don't even know where to look for help, or even to get started.

  1. In JavaScript style, how would you go about representing the Animal kingdom, with inheritance? I would use a class Animal, and then a Class Dog, and instantiate objects of dogs, for example. This is not the JavaScript way.

An example of non-JavaScvript:

class Animal{
    constructor(aName){
        this.name = aName;
    }
}

class Dog extends Animal{
    constructor(){
        super(aName);
        this.type = "Furry dog";
    }
}

let myDog = new Dog("Boby");
  1. What is the JavaScript way of doing this?

At this point, I am looking for guidance. After trying I was unable to find anything helpful, mainly because I believe I am so lost that I am not even searching for the right thing.

Thanks in advance.

Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266
  • 5
    There are very strong voices on both sides of the spectrum. OOP is fine in JavaScript for many use cases, but it is nice to get to know the underlying prototype system. I like [**Eric Elliot's blog posts**](https://medium.com/javascript-scene/common-misconceptions-about-inheritance-in-javascript-d5d9bab29b0a#.ncfz8glrr) on the matter. – Tholle Feb 03 '17 at 08:31
  • Please note that questions asking for recommend (*Do you recommend*), will attract downvotes and closing votes as over SO, we do not recomment – Rajesh Feb 03 '17 at 08:31
  • 1
    There's plenty of discussions and help regarding OO Javascript, but it's so different from the enforced discipline of Java or C# (I'm a C# developer) that it's almost like it doesn't really exist. As already mentioned, prototyping is useful to understand and that will give you many of the features you're familiar with from inheritance. Just don't expect too much abstraction. – Reinstate Monica Cellio Feb 03 '17 at 08:33
  • 1
    @Rajesh He's asking for discussion - not a recommendation of a solution (a library, 3rd party solution etc.). This is well within the realms of a SO question. – Reinstate Monica Cellio Feb 03 '17 at 08:34
  • @Archer Yes and thats why I choose to comment instead of voting to close. But still I see 4 close votes. So soon it will end up being closed – Rajesh Feb 03 '17 at 08:35
  • Have a look at TypeScript (https://www.typescriptlang.org/) – mvermand Feb 03 '17 at 08:35
  • 1
    Obligatory link: https://pbs.twimg.com/media/CLWv31DWgAAvvsj.jpg – GOTO 0 Feb 03 '17 at 08:37
  • 2
    @Rajesh It would have been more productive to explain why it *shouldn't* be getting close votes then :) – Reinstate Monica Cellio Feb 03 '17 at 08:37
  • While "Animal > Dog -> fido" is the canonical OOP example, how often have you actually needed to represent it in programming? The other canonical example are UI elements (Widget > Label...), but again this is not often the subject of a JavaScript program. I believe you will find you do not need class hierarchies nearly as much as you are taught to think. – Amadan Feb 03 '17 at 08:37
  • 1
    @Archer will keep that in mind :-) – Rajesh Feb 03 '17 at 08:38
  • I edited my question to not ask for a recommendation. I believe it fits better SO standards now. Can we reopen it ? – Flame_Phoenix Feb 03 '17 at 08:42
  • The question will be better if you will post code examples that trouble you. The best way possible is to analyze the output from Typescript and Babel (5, because 6 is littered with helpers). – Estus Flask Feb 03 '17 at 08:46
  • I believe there are many people interested in it, and it would be beneficial. Besides now I ask a concrete Question answerable with programming and code. Please find in your hearts the love to give this a second chance. – Flame_Phoenix Feb 03 '17 at 08:46
  • Done, I have added an example on Non-JavaScript. I believe this is as good as its gonna get! – Flame_Phoenix Feb 03 '17 at 08:50
  • are you looking for something like [this](http://phrogz.net/js/classes/OOPinJS2.html)? – www0z0k Feb 03 '17 at 08:51
  • A basic implementation of [Animal Kingdom](https://jsfiddle.net/RajeshDixit/wv35eaxk/) in ES5 would look like this. But you can try following approach: http://stackoverflow.com/a/1169656/3783478 – Rajesh Feb 03 '17 at 08:57
  • 1
    OOP with inheritance in Javascript works pretty much the same as elsewhere, only that there's no distinct concept between an "inert" "blueprint" of an object and the actual object, but that everything is an object or function, a "class" is essentially a constructor function and instantiating an object is a procedure for putting together the object from specific parts in the right order. How exactly prototypical inheritance works has been explained before. Are you asking for anything beyond that? Is there a specific aspect which hasn't been covered yet? – deceze Feb 03 '17 at 09:01
  • 3
    Recommended free (as in beer) reading: [Exploring ES6](http://exploringjs.com/) by @AxelRauschmayer and [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS#titles) series. – Estus Flask Feb 03 '17 at 09:31

1 Answers1

17

As far as I know, JavaScript is a Prototype based language with First-class functions, as you can read here.

Now. Actually this is just a style of OPP which means you will be working and thinking about objects and inheritance. You just have to know that, in JavaScript, there are no classes but we have prototypes instead. But remember. It's all about the functions.

Object constructors

To make your own object definition, you would do as follows:

function Animal() {
    this.name = null;
    this.age = 0;
    this.genus = null;
    this.isWild = true;
};

Animal.prototype.hasName = function() {
    return this.name !== null;
};

Animal.prototype.isItWild = function() {
    return this.isWild;
};

// Here we create an instance of Animal
var someAnimal = new Animal();
// Let's give it a name
someAnimal.name = 'Dobby';
console.log('Hey there. My pet name is %s', someAnimal.name);
console.log('is it wild? %o', someAnimal.isWild);

Now you have your Animal prototype. Let's see how to extend its properties to create the Dog prototype:

function Dog() {
    this.genus = 'Canis';
    this.race = 'unknown';
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
    console.log('rrouff!');
};

Let's create a race of dog now:

function SiberianHusky(name, age) {
    this.name = name;
    this.age = age;
    this.race = 'Siberian Husky';
}

SiberianHusky.prototype = Object.create(Dog.prototype);
SiberianHusky.prototype.constructor = SiberianHusky;

// Let's create our Siberian Husky
var myPet = new SiberianHusky('Bobby', 5);
// Aww. It is barking!
myPet.bark();

The prototype object

You can see in the examples that every definition is using the Object prototype. That is used to define how an object is. You can think of it as the class definition.

How to avoid the over-use of the prototype property

Instead of writing to the prototype every time, you can do the following:

Animal.prototype = {
    name: null,
    age: 0,
    genus: null,
    isWild: true,
    hasName: function() { ... }
    isItWild: function() { ... }
}

To fully understand the concept of prototypes and how they inherit from each other, you can check this.

Last notes

JavaScript is a multi-paradigm language. You can use the Object Oriented Programming Paradigm, the Imperative Programming Paradigm and the Functional Programming Paradigm, wich means that you can program the same application in a lot of different ways.

Some helpful links

https://en.wikipedia.org/wiki/JavaScript

https://en.wikipedia.org/wiki/Prototype-based_programming

Cheers.

Chrisuu
  • 272
  • 3
  • 13
Asier Paz
  • 631
  • 1
  • 5
  • 16
  • 1
    This is only one way to work with prototypes. Using object constructors is not at all necessary, and neither is the `.prototype` property. – nils Feb 03 '17 at 09:21
  • 3
    I just shared my poor knowledge trying to help. If you can do it better, I encourage you to post an answer instead of a comment. Thanks for the input though. – Asier Paz Feb 03 '17 at 10:11
  • You had Classes in Js since 2015 – George Tiganila Mar 16 '21 at 17:07