2

I would like to know by some form of reflection or other means if a given ES6 class has a user-written non-default constructor, or not.

0

2 Answers 2

1

Assuming that user-provided constructor has one argument or more, you can do that by checking the length property of the function(class). But if the constructor takes no argument, there is simply no way as far as I know

function Person(fName, lName) {
    this.firstName = fName;
    this.lastName = lName
}
console.log(Person.length);

function Person2() {}
console.log(Person2.length);

class Person3 {
    constructor(f,l) {}
}
console.log(Person3.length);

class Person4 {
}
console.log(Person4.length);

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

Comments

1

You can invoke the Classname.prototype.constructor.toString() (where Classname is the inspected class name) and get the source string for the class. Which you can then parse and see if it was a constructor declared or not.

Presumably, you need a decent parser for that, but it's another story.

References:

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.