Reputation: 2263
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.
Upvotes: 2
Views: 128
Reputation: 254916
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:
Upvotes: 1
Reputation: 6814
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);
Upvotes: 1