Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!