export class InvalidCredentialsError extends Error {
constructor(msg) {
super(msg);
this.message = msg;
this.name = 'InvalidCredentialsError';
}
}
As you can see above, I'm writing InvalidCredentialsError
twice. Is there a way to somehow get the class name already in the constructor method and set it? Or does the object have to be instantiated?
Access the name property on the object's constructor to get the class name of the object, e.g. obj.constructor.name . The constructor property returns a reference to the constructor function that created the instance object. Copied!
The name of the constructor must be the same as the name of the class and, if you provide more than one constructor, the arguments to each constructor must differ in number or in type from the others. You do not specify a return value for a constructor.
class A { into x; public: A(); //Constructor }; While defining a constructor you must remember that the name of constructor will be same as the name of the class, and constructors never have return type.
In browsers with native ES6 class support, this.constructor.name
will display the InvalidCredentialsError. If you transpile the code with Babel it will show Error.
Without Babel (use on Chrome or another browser that supports class):
class InvalidCredentialsError extends Error {
constructor(msg) {
super(msg);
console.log(this.constructor.name);
this.message = msg;
this.name = 'InvalidCredentialsError';
}
}
const instance = new InvalidCredentialsError('message');
With Babel:
class InvalidCredentialsError extends Error {
constructor(msg) {
super(msg);
console.log(this.constructor.name);
this.message = msg;
this.name = 'InvalidCredentialsError';
}
}
const instance = new InvalidCredentialsError('message');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With