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.
classis onlysyntax sugar, it still uses function behind the scenesconst newShip = new RigidBody();is not necessary sincenewShipwill never be aninstanceof RigidBody. Despite calling the factory with thenewoperator, just a new canvas element is returned (as intended). Nothisbinding is involved. Therefore the OP should renameRigidBodytocreateRigidBodywhich by name tells it's a factory function with no need fornew.