Normal
Normal

Reputation: 3646

Changing the return value of a constructor

Based on the JavaScript specification, a class constructor returns the value of this when it gets called by the new keyword.

Can we change the return value to something else? If yes, is it a bad practice? I'm asking if it is a bad practice, for instance, it could be because of some stuff related to the inheritance. For example

class Car {
  constructor(color) {
    this.color = color
    return this.printColor
  }
  printColor = () => {
    console.log(this.color)
  }
}

const car1 = new Car('red')
car1()

Is it a new idea, or is it something normal and the people normally do everyday?

Upvotes: 4

Views: 1473

Answers (1)

Bergi
Bergi

Reputation: 664548

A class constructor returns the value of this when it gets called by the new keyword.

See What is the 'new' keyword in JavaScript? and How does the new operator work in JavaScript? for details.

Can we change the return value to something else?

Yes, as long as it is an object, you can override the default by using return - as you did in your example code. See What values can a constructor return to avoid returning this? and What is returned from a constructor? for how that works exactly.

If yes, is it a bad practice?

Yes. Having new Car return a function and not a Car instance is weird and unexpected. People do not do this every day, and they shouldn't start doing it :-)

The only exception is the singleton pattern (which of course is problematic itself), where the constructor may return the singleton instance instead of a new one. (There are however other ways to write JS code for creating singletons, which avoid constructors altogether.)

Upvotes: 2

Related Questions