0

I have two classes in Javascript like this:

class Parent {
    constructor(){
        console.log(typeof this);
    }
}

class Child extends Parent {
    constructor(){
        super();
    }
}

In the Parent class, I would like to know what class instantiated it. However, typeof just returns object. Is there any other way to solve this?

3
  • 1
    What exactly do you need this for? This sounds like an XY problem. Commented Sep 29, 2016 at 18:47
  • I intend to let the Parent class handle methods like save and get, and unless anything else is specified, it will look in tables that are named lowercase of the calling class. So if I instantiate a child, and run child.save() i'll let the Parent.save method save the object to a table called "child" Commented Sep 29, 2016 at 19:14
  • I would recommend to pass the table name explicitly as a parameter to the parent constructor. Relying on the child constructor name has several problems: it might not work in pre-ES6 environments, it breaks the LSP, and there might be anonymous subclasses or duplicate names. Commented Sep 29, 2016 at 19:57

2 Answers 2

3

this.constructor will return the constructor function with which the objet was created. You could access this.constructor.name if you need a string.

class Parent {
    constructor(){
        console.log(this.constructor.name);
    }
}

class Child extends Parent {
    constructor(){
        super();
    }
}

new Child(); // Child
new Parent(); // Parent

Sign up to request clarification or add additional context in comments.

Comments

1

Since you are using ES6 classes, new.target is what you are looking for. But notice that it's usually an antipattern to let a constructor's behaviour depend on particular child classes.

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.