0

I am using a javascript library that is implementing ES6 class in their modules. I have not used classical inheritance in javascript and would like to essentially "undo" their class implementation. Is there a way I can take those classes and still use them in a Factory/Composition approach. I want to take advantage of JS prototypal inheritance and easy compostability of objects. The following is an example of what I have so far. Ultimately I am trying to avoid using class and new, because I am not used to using it in JavaScript. Could anyone tell me if I am approaching this in the right way or if I am just wasting my time, thank you.

class Example {

 constructor(id) {
  this.id = id;
 }

 getID() {
  console.log(this.id);
 }
}


function convertClassToObject(theClass) {
 var x = new theClass();
 var newX = Object.create(x);
 return newX;
}

var NewPrototype = convertClassToObject(Example);

function NewFactory(options) {
 var x = Object.assign(Object.create(NewPrototype), options);
 return x;
}

var NewInstance = NewFactory({id: 123456789});
4
  • 3
    class is just syntactic sugar around constructor and prototype constructs. Everything is still prototype-based underneath. new Example(id) is equivalent to var obj = Object.create(Example.prototype); obj.constructor(id). Commented Apr 3, 2017 at 18:43
  • Oh perfect, I can just link prototype with Object.create and use that instance for a factory, got it. Commented Apr 3, 2017 at 18:49
  • 2
    @MikeC Except in ES6, where constructors must be invoked with new (or super() or Reflect.construct) Commented Apr 3, 2017 at 18:53
  • 1
    Not sure what you mean by composition here? You can also do the object-oriented one with prototype instances, class doesn't change anything there Commented Apr 3, 2017 at 18:54

1 Answer 1

2

You should rather get used to new, it's much simpler than doing prototypical inheritance in factories.

Of course, it's trivial to convert a constructor function to a factory function:

function classToFactory(constr) {
    return (...args) => new constr(...args);
}

const makeExample = classToFactory(Example);
const newInstance = makeExample(123456789); // no `new` any more
Sign up to request clarification or add additional context in comments.

1 Comment

I guess I could try getting used to the new keyword. Thank you for your insight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.