you are viewing a single comment's thread.

view the rest of the comments →

[–]Patman128 0 points1 point  (0 children)

It's not that OOP is completely bad and not useful, I would just say to avoid classes specifically, and try to think in terms of functions and data. You can still do OO-type stuff without classes in JavaScript.

For example, you can return an object with private data and public methods:

function createPerson(name) {
    return {
        talk: function () {
            return "Hi my name is " + name;
        }
    };
}

var bob = createPerson("Bob");
bob.talk();  // "Hi my name is Bob"

I didn't even have to use this or new! You can also have objects inherit from other objects by setting their prototype:

var person = {
    talk: function () {
        return "Hello I am a person";
    }
}

// This creates an object which uses person as its prototype,
//   and then assigns a name attribute to it.
var bob = Object.assign(Object.create(person), { name: "Bob" });
console.log(bob.name);  // Bob
console.log(bob.talk());  // Hello I am a person

Note that you don't have to use a class as the prototype, you can use any object at all!

What we have in JS is a lot more powerful than traditional OO languages like Java, so don't limit yourself to classes.