1

Years ago I used this technique because I did not know how to do it "right" with prototype. It's a technique I call Christmas tree OOD. You make a function which is like a constructor that makes a new object, attaches new properties to it, like a Christmas tree, and return the reference to it. Here is an example:

function RigidBody() {
    const newRB = document.createElement('canvas');
    
    newRB.dataMember = 5;
  
    newRB.memberFunction = function() {
        // do important rigid body stuff
    }

    return newRB;
}

Then you can use this function as a kind of base object to make other derived objects.

function Ship(locX, locY) {
    const newShip = new RigidBody();

    newShip.otherDataMember = 34;

    newShip.otherMemberFunction = function() {
        // some other important ship specific stuff to do
    }

    return newShip;
}

You can see that this simple thing I did can make N number of objects with a full "class" hierarchy of objects. Then you can just make an object of the derived object.

    const myShip = new Ship(100, 200);

I use class now and I don't plan on using this in the future but I'm curious to know if others have used this technique and if it has a name.

  • 1
    see: [Factory Vs Prototype - What to use when?](https://stackoverflow.com/questions/20043279/factory-vs-prototype-what-to-use-when) and [Inheritance with factory method/class pattern](https://stackoverflow.com/questions/43864114/inheritance-with-factory-method-class-pattern) which links to [Learning JavaScript Design Patterns](https://www.patterns.dev/posts/classic-design-patterns/) – pilchard Jun 03 '22 at 21:21
  • They say `class` is only `syntax sugar`, it still uses function behind the scenes – Jupri Jun 03 '22 at 21:22
  • Factory usually means returning potentially N number of different kinds of objects depending on a parameter. So it's kind of like factory. This technique definitely works but I would not use it for large programs. – John Vonachen Jun 03 '22 at 23:10

1 Answers1

1

It's still called OOP, since you're working with objects. Redefining member functions inside the constructor (when not necessary for this-binding) instead of putting them on the prototype is considered a bad practice, but doesn't change functionality or modelling.

Your technique for creating derived objects is known as parasitic inheritance, a term coined by Douglas Crockford afaict.

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
  • After reading the links you included, especially about parasitic Inheritance I've decided that the way I did it is perfectly kosher. I did remove the "new"s though. Thanks. – John Vonachen Jun 04 '22 at 03:19