Facebook Pixel
this in Constructors and the new Keyword in JavaScript

What happens if a constructor returns an object in JavaScript?

The answer

The returned object is used instead of this. If you return a primitive (number, string) or nothing, this is returned. This is why constructors should usually not return anything.

More FAQs in this in Constructors and the new Keyword in JavaScript

It creates a new empty object, sets this to that object inside the function, runs the function body, and returns this (the new object) unless the function returns its own object.

this becomes the global object (or undefined in strict mode). Properties get added to window instead of a new object. The function returns undefined. This is a common bug with function constructors.

Yes. Calling a class constructor without new throws TypeError: Class constructor X cannot be invoked without 'new'. This prevents the forgotten-new bug that function constructors have.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.