Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class name in constructor

Tags:

ecmascript-6

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?

like image 920
basickarl Avatar asked Jan 17 '17 13:01

basickarl


People also ask

How do I find the class name of an object?

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!

Is constructor name same as class name?

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.

How do we define a constructor when class name is?

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.


1 Answers

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');
like image 99
Ori Drori Avatar answered Oct 17 '22 01:10

Ori Drori