0

I have next classes:

class Type {
    static fromObject(obj = {}) {
        return <new descendant object>
    }
}

class CustomType1 extends Type {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
}

class CustomType2 extends Type {
    constructor(c, d) {
        this.c = c;
        this.d = d;
    }
}

const t1 = CustomType1.fromObject({a:1, b:2})
const t2 = CustomType2.fromObject({c:3, d:4})

Expected result: t1 is instance of CustomType1 and t2 is instance of CustomType2

Question: It's possible to access child's class or prototype or constructor from parent class through static context in order to use method as factory.

3
  • You might want to try using new.target to get access to the constructor: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented May 30, 2018 at 7:32
  • 1
    For CustomType1.fromObject the this in fromObject refers to CustomType1, and for CustomType2.fromObject the this refers to CustomType2, isn't that enough in your case? Commented May 30, 2018 at 7:33
  • 2
    Mostly you're just looking for return new this(). The trickier part is to deconstruct the object into positional arguments… Commented May 30, 2018 at 7:37

1 Answer 1

1

The this within the fromObject will like for any other function that you call (except arrow function that do context binding) refer to object on which it is called, so in your case, it would be CustomType1 and CustomType2. CustomType1 and CustomType2 are the constructor of those classes.

class Type {
 static fromObject(obj = {}) {
    return new this(obj.a, obj.b)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.